如何在MobX操作中包含多个等待呼叫



我正在开发一个应用程序,该应用程序需要在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处理操作的方式,此代码似乎无法正确执行。根据文件:

@操作仅适用于代码块,直到第一个等待。和在每个等待之后,将启动一个新的异步函数,因此在等待,状态修改代码应该包装为操作。

文档中给出的示例使用runAsAction,我在以下代码中尝试过:

@action.bound
async updateLastMintedToken() {
const tokenInstance = await this.token.deployed();
runInAction(async function() {
const result = await tokenInstance.lastTokenMinted.call();
this.lastTokenMinted = result.toNumber();
});
}

不幸的是,这没有起作用,因为thisrunInAction调用中变得未定义,所以我无法更改状态。

非常感谢在一个操作中运行多个异步调用的任何方向!

您可以使用箭头函数将runInAction中的上下文设置为与updateLastMintedToken函数相同的上下文

@action.bound
async updateLastMintedToken() {
const tokenInstance = await this.token.deployed();
runInAction(async () => {
const result = await tokenInstance.lastTokenMinted.call();
this.lastTokenMinted = result.toNumber();
});
}

最新更新