【问题标题】:Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined [duplicate]未捕获(承诺中)TypeError:无法读取未定义的属性“setState”[重复]
【发布时间】:2017-03-04 12:27:50
【问题描述】:

对我来说,这个错误在使用 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 } ]

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

【问题讨论】:

  • 请发布异常的完整堆栈跟踪(应该在开发控制台中)

标签: javascript node.js reactjs es6-promise


【解决方案1】:

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

【讨论】:

  • 嗨 T.J. Crowder 我解决了我的问题,但很困惑为什么会发生这种情况,你能在上面简要解释一下吗?
  • @shazimali - 查看答案here。从根本上说,这是为了确保 this 是您希望它在函数中出现的内容。通常,this 由函数的调用方式设置(参见我贫血的小博客上的here 和/或this aged post)。但是箭头函数关闭 this(就像关闭一个变量)。所以无论 thisgetdata 调用中是什么,它在 axios 回调中也是如此。
  • @shazimali - FWIW,我在新书的第 3 章中详细介绍了箭头功能以及 this 的工作原理;如果您有兴趣,请在我的个人资料中链接。
猜你喜欢
  • 2017-12-24
  • 2020-03-10
  • 2019-05-16
  • 2018-05-28
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2018-06-03
相关资源
最近更新 更多