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

如何在TypeScript中获取Solidity合约公共状态变量值?解决undefined问题

解决方法:获取Solidity合约公共状态变量返回undefined的问题

你的代码核心问题是Promise嵌套时未正确返回异步结果:await后的then回调里,调用contract.highestBid.call()后没有返回这个Promise,导致整个await表达式最终拿到的是undefined。

下面是两种可行的修正方案:

方案1:用async/await简化写法(推荐)

直接用await替代嵌套的then,代码更清晰且不易出错:

async getHighestBid() {
    this.smartAuction.setProvider(this.provider);
    // 先获取已部署的合约实例
    const contract = await this.smartAuction.deployed();
    // 调用公共变量自动生成的view函数
    const result = await contract.highestBid.call();
    console.log(result);
}

方案2:修正原有的then链式写法

如果要保留then的写法,需要确保在回调中返回call()的Promise:

async getHighestBid() {
    this.smartAuction.setProvider(this.provider);
    let result = await this.smartAuction.deployed()
        .then(function(contract) {
            // 必须返回call()的Promise,await才能拿到最终结果
            return contract.highestBid.call();
        });
    console.log(result);
}

额外注意事项

  • 确保你的provider网络配置和合约部署的网络完全一致(比如都是Goerli测试网或主网)
  • Solidity中的public状态变量会自动生成同名的view函数,所以用.call()调用是正确的方式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:31:08