如何在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
相关产品推荐
相关产品推荐

