如何在 MobX 操作中包含多个等待调用
How to include multiple await calls in MobX action
我正在开发一个需要在 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 处理动作的方式,这段代码似乎无法正确执行。根据 docs:
@action only applies to the code block until the first await. And
after each await a new asynchronous function is started, so after each
await, state modifying code should be wrapped as action.
文档中给出的示例使用 runAsAction
,我在以下代码中尝试使用:
@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
调用中变得未定义,所以我无法改变状态。
非常感谢在一个动作中 运行 多个异步调用中的任何方向!
您可以使用箭头函数将 runInAction
中的上下文设置为与 updateLastMintedToken
函数
相同的上下文
@action.bound
async updateLastMintedToken() {
const tokenInstance = await this.token.deployed();
runInAction(async () => {
const result = await tokenInstance.lastTokenMinted.call();
this.lastTokenMinted = result.toNumber();
});
}
我正在开发一个需要在 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 处理动作的方式,这段代码似乎无法正确执行。根据 docs:
@action only applies to the code block until the first await. And after each await a new asynchronous function is started, so after each await, state modifying code should be wrapped as action.
文档中给出的示例使用 runAsAction
,我在以下代码中尝试使用:
@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
调用中变得未定义,所以我无法改变状态。
非常感谢在一个动作中 运行 多个异步调用中的任何方向!
您可以使用箭头函数将 runInAction
中的上下文设置为与 updateLastMintedToken
函数
@action.bound
async updateLastMintedToken() {
const tokenInstance = await this.token.deployed();
runInAction(async () => {
const result = await tokenInstance.lastTokenMinted.call();
this.lastTokenMinted = result.toNumber();
});
}