Uncaught(在promise中)TypeError:无法读取未定义的属性'setState'

对我来说,这个错误是相当经常使用axios.can't setstate与未定义的属性。第八我得到实际的回应。我很困惑。任何解决scheme将不胜感激。

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

this在一个标准函数中通常是由它的调用方式决定 ,而不是函数的创build位置。 所以this在这里的callback函数和this外面的不一样:

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

然而,箭头函数closures了他们的上下文,所以:

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