我在react中使用异步等待时遇到问题,这是我的.babelrc
{
"presets": [
["es2015", {"modules": false}],
"stage-2",
"react"
],
"plugins": [
"react-hot-loader/babel",
"transform-async-to-generator",
["transform-runtime", {
"polyfill": false,
"regenerator": true
}]
]
}使用async await调用api没有问题,但由于this未定义,无法使用setState
class App extends Component {
testAsync = async () => {
const { body } = await requestOuter('GET', 'https://api.github.com/users')
console.log(body) //working, body is bunch of array of object
this.setState({body}) //this is not defined error?
}
render() {
return <div>
<button onClick={() => this.testAsync()}>test async</button>
{(this.state.body || []).map(o => o.login)}
</div>
}
}发布于 2018-03-14 20:53:58
this是对正在执行的当前对象的引用,promise this内部与应用程序范围不同。
尝试:
<button onClick={() => {var self=this; this.testAsync(self);}}>test async</button>。
testAsync = async (self) => {
const { body } = await requestOuter('GET', 'https://api.github.com/users')
console.log(body) //working, body is bunch of array of object
self.setState({body}) ;
}您必须尝试此方法的变体。一种变体应该根据应用范围而工作。
发布于 2018-03-15 10:54:21
这很管用。
async testAsync() {
const { body } = await requestOuter('GET', 'https://api.github.com/users')
console.log(body) //working, body is bunch of array of object
this.setState({body}) //this is not defined error?
}并且我必须在jsx中使用箭头函数
更新:这是由react-hot-loader引起的,哇哦没想到!https://github.com/gaearon/react-hot-loader/issues/391
https://stackoverflow.com/questions/49275060
复制相似问题