Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined
Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined
对我来说,这个错误在使用 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'))
标准函数中的 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
})
})
}
对我来说,这个错误在使用 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'))
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
})
})
}