我正在使用MobX操作中的await
语法处理需要多次调用的应用。一个典型的例子如下:
@action.bound
async mintToken() {
const tokenInstance = await this.token.deployed();
await tokenInstance.mint(1, { from: this.account });
await this.updateLastMintedToken();
await this.updateTokenDetails();
}
但是,由于MobX处理操作的方式,此代码似乎无法正确执行。根据{{3}}:
@action仅适用于代码块,直到第一次等待。和 在每次等待之后,启动一个新的异步函数,所以在每次之后 await,状态修改代码应该被包装为动作。
文档中给出的示例使用runAsAction
,我在以下代码中尝试使用{<1}}:
@action.bound
async updateLastMintedToken() {
const tokenInstance = await this.token.deployed();
runInAction(async function() {
const result = await tokenInstance.lastTokenMinted.call();
this.lastTokenMinted = result.toNumber();
});
}
不幸的是,这并没有奏效,因为this
调用中runInAction
未定义,因此我无法改变状态。
非常感谢在动作中运行多个异步调用的任何方向!
答案 0 :(得分:1)
您可以使用箭头功能将runInAction
内的上下文设置为与updateLastMintedToken
函数相同的上下文
@action.bound
async updateLastMintedToken() {
const tokenInstance = await this.token.deployed();
runInAction(async () => {
const result = await tokenInstance.lastTokenMinted.call();
this.lastTokenMinted = result.toNumber();
});
}