我在使用async await时出现问题,这是我的.babelrc
foo/
我没有问题使用async await来调用api但不能setState因为{
"presets": [
["es2015", {"modules": false}],
"stage-2",
"react"
],
"plugins": [
"react-hot-loader/babel",
"transform-async-to-generator",
["transform-runtime", {
"polyfill": false,
"regenerator": true
}]
]
}
没有定义
this
答案 0 :(得分:0)
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}) ;
}
你必须尝试改变这种方法。一种变体应该适用于应用范围。
答案 1 :(得分:0)
这有效
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