未捕获(在承诺中)TypeError:无法读取未定义

时间:2016-10-22 07:17:39

标签: javascript node.js reactjs es6-promise

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

杰森的回复 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 } ]

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'))

1 个答案:

答案 0 :(得分:22)

标准函数中的

this通常由如何调用决定,而不是创建函数的位置。因此,此处回调函数中的this与其外的this不同:

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

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

然而,箭头函数靠近其上下文的this,所以:

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

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