【发布时间】:2018-03-14 10:16:37
【问题描述】:
我在 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 没有问题,但无法 setState,因为 this 未定义
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>
}
}
【问题讨论】:
-
你使用的是什么版本的
transform-async-to-generator:github.com/babel/babel/issues/2765 -
您像 var 一样定义 testAsync,.. 您希望它成为该类的方法,只需执行 ..
async testAsync() {事实上,对于 Babel,您所做的事情我得到了一个错误. -
你能在这个 sn-p 的 babel 编译后发布输出吗?
-
@Keith 那有什么问题?假设一个函数可以分配给一个 var?
-
@SharonChai
what's wrong with that?你定义了一个类,Component {这之后的代码不是任何函数的主体,甚至不是构造函数。所以这基本上是一个语法错误。为什么不尝试我的建议?.. 简单地说,async testAsync() {,这就是您将方法绑定到类的方式,无需分配。
标签: javascript reactjs ecmascript-6 babeljs