未捕获(承诺)TypeError:无法读取undefined属性'setState'

问题描述:

对我来说,这个错误是相当经常使用axios.can't setstate与未定义property.Eighthough我得到实际的回应。我很困惑。解决方案将不胜感激。未捕获(承诺)TypeError:无法读取undefined属性'setState'

JSON通过 爱可信回复回复

[ { 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')) 
+0

请张贴的完整堆栈跟踪异常(应该在dev控制台中) – Ivan

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