Uncaught (in promise) TypeError: Cannot read setState property from undefined

For me, this error quite often occurs when using axios.can't setstate with the undefined property. If I get the actual answer. I'm pretty confused. Any solution would be appreciated.

Json answer from axios answer

[ { 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')) 
+7
javascript es6-promise reactjs
source share
1 answer

this in a standard function is usually determined by what it is called, not where the function was created. Thus, this in the callback function here does not match this outside of it:

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

The arrow functions, however, are closed by this their context, therefore:

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

All Articles