未捕获(在承诺中)TypeError:无法读取未定义的属性"setState"

Nan*_*ane 9 javascript node.js reactjs es6-promise

对我来说,使用axios时经常出现这种错误.我无法使用未定义的属性设置状态.尽管我得到了实际的回应.我很困惑.任何解决方案将不胜感激.

json通过axios回复回复

[ { main: 1,
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    cid: 6,
    '$created': '2016-10-21T11:08:08.853Z',
    '$updated': '2016-10-22T07:02:46.662Z',
    stop: 0 } ]
Run Code Online (Sandbox Code Playgroud)

code.js

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
    export default class Main extends React.Component{
        constructor(props){
            super(props);
            this.state = {
                status:[]
            }
        }
        componentDidMount(){

            this.getdata()
        }
        getdata(){
            axios.get('/getactions')
                .then(function (data) {
                    console.log(data.data);

                    this.setState({
                        status:data
                    })
                })
        }

        render(){
            console.log(this.state)
            return(
                <div>
                   <button >Left</button>

                </div>
            )
        }
    }


    ReactDOM.render(<Main/>,document.getElementBy

Id('app'))
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 23

this标准函数中的函数通常取决于它的调用方式,而不是函数的创建位置.所以this在回调函数中这里不一样this:

getdata(){
    axios.get('/getactions')
        .then(function (data) {
            console.log(data.data);

            this.setState({
                status:data
            })
        })
}
Run Code Online (Sandbox Code Playgroud)

然而,箭头函数接近this其上下文,因此:

getdata(){
    axios.get('/getactions')
        .then(data => {                // <== Change is here
            console.log(data.data);

            this.setState({
                status:data
            })
        })
}
Run Code Online (Sandbox Code Playgroud)