【发布时间】:2016-12-05 08:17:24
【问题描述】:
下面是一个 ES2015 类中的方法。
它不能是箭头函数,因为它是异步函数。
但由于它不是箭头函数,“this”不在作用域内,所以我无法执行 setstate 之类的操作。
有人可以建议我如何将其纳入范围吗?谢谢!
async doSubmit(email_address, password) {
this.setState({isSubmitting: true, error: null})
try {
let data = await this.props.app.server.doSignIn(email_address, password)
} catch (jqXHR) {
let errorType = (jqXHR.status >= 400 && jqXHR.status < 500) ? 'application' : 'system'
let errorMessage = (errorType === 'application') ? jqXHR.responseJSON.description : jqXHR.error
this.setState({error: errorMessage, isSubmitting: false})
}
// following a signin event make sure the user image changes
this.props.app.reloadProfileImages()
try {
await this.props.app.initializeClouds()
} catch (err) {
xog('err', err)
this.setState({error: errorMessage, isSubmitting: false})
}
this.postSignIn(data)
}
【问题讨论】:
-
箭头函数也可以是异步的。
const doSubmit = async (email_address, password) => { ... } -
@CodingIntrigue 你能指点我一些明确的参考来确认这一点吗?到目前为止我所了解的一切都说“没有异步箭头函数”。
-
你能把
this放到一个局部变量中吗?例如var _this = this; -
@qxz 在课堂情况下这很困难,因为您需要将其存储在
doStuff的范围之外,但仍然允许它访问
标签: javascript reactjs asynchronous scope ecmascript-6