You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React组件调用导入的异步函数时.then()返回undefined问题排查

为什么导入的异步函数在React中返回undefined?

你遇到的问题核心很明确:你的GetOwnBalance函数没有返回实际的余额值,导致后续.then()回调里的value变成了undefined。

问题根源拆解

你把GetOwnBalance声明成了async函数,但它内部的逻辑有两个关键问题:

  1. 调用nftContract.methods.getBalance().call()后,你只是在.then()里打印了余额,没有把这个值返回出去;
  2. 整个GetOwnBalance函数也没有返回这个promise链,async函数如果没有显式return,默认会返回一个resolve为undefined的promise。

这就导致当你在App.js里调用GetOwnBalance().then(...)时,拿到的只能是undefined。

修复方案

有两种简洁的修复方式,选你习惯的一种就行:

方式一:用async/await简化(推荐)

直接await合约调用的结果,然后返回它:

// index.js
const GetOwnBalance = async () => {
  if (!isInitialized) {
    await init();
  }
  // 直接await call方法的结果
  const balance = await nftContract.methods.getBalance(selectedAccount).call();
  console.log("Intermediate balance : " + balance);
  return balance; // 关键:返回余额值
};
export default GetOwnBalance;

方式二:保持.then写法,返回promise链

如果你更习惯用.then,需要确保把整个promise链返回,并且在内部的.then里返回余额:

// index.js
const GetOwnBalance = async () => {
  if (!isInitialized) {
    await init();
  }
  // 关键:返回这个promise链
  return nftContract.methods
    .getBalance(selectedAccount)
    .call()
    .then((balance) => {
      console.log("Intermediate balance : " + balance);
      return balance; // 把余额传递给下一个then
    });
};
export default GetOwnBalance;

可选优化:简化App.js的fetchBalance

修复完GetOwnBalance后,你也可以把fetchBalance改成async函数,让代码更清晰:

// App.js
async function fetchBalance() {
  const value = await GetOwnBalance();
  setBalance(value);
  console.log("Final Balance : " + value);
}

这样修改后,点击按钮就能正常获取并显示余额了。

内容的提问来源于stack exchange,提问作者Shekhar Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 18:29:06