[英]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處理動作的方式,該代碼似乎無法正確執行。 根據文檔 :
@action僅適用於代碼塊,直到第一次等待。 並且在每次等待之后啟動一個新的異步函數,因此在每次等待之后,狀態修改代碼應包裝為動作。
docs中給出的示例使用runAsAction
,我在以下代碼中嘗試過:
@action.bound
async updateLastMintedToken() {
const tokenInstance = await this.token.deployed();
runInAction(async function() {
const result = await tokenInstance.lastTokenMinted.call();
this.lastTokenMinted = result.toNumber();
});
}
不幸的是,這沒有用,因為在runInAction
調用中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();
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.