【问题标题】:I have an error when reading a method with web3 (call)使用 web3(调用)读取方法时出现错误
【发布时间】:2021-08-28 02:23:34
【问题描述】:

我正在尝试学习如何与 web3 集成,但我遇到了一些问题。 (正常我刚开始)

但是有一个问题我解决不了。

Uncaught TypeError: Cannot read property 'retrieve' of undefined

我尝试调用一个函数,但它不起作用,我不知道如何解决它。

代码如下:

const abi_c = [{"inputs": [],"name": "retrieve","outputs": [{"internalType": "uint256","name": "","type": "uint256"}],"stateMutability": "view","type": "function"},{"inputs": [{"internalType": "uint256","name": "num","type": "uint256"}],"name": "store","outputs": [],"stateMutability": "nonpayable","type": "function"}];
const account = "0x644f1439DBfc743853031d79021890af54bCA8Ae";

const web3js = new Web3(window.ethereum);
ethereum.autoRefreshOnNetworkChange = false;

var contract = web3js.eth.contract(abi_c, account);
var result = contract.methods.retrieve().call();
console.log(result);

【问题讨论】:

    标签: ethereum web3 web3js


    【解决方案1】:

    您需要使用 new 关键字实例化 web3js.eth.Contract 类。

    var contract = new web3js.eth.Contract(abi_c, account);
    

    没有它,var contract 仅指向未实例化的定义和静态属性。

    另外,请注意Contract (docs) 中的大写 C


    那么你会遇到另一个问题。

    .call() 方法返回一个Promise,因此您需要使用await 表达式(在async 函数中)或回调函数来解决它。

    // needs to be in an async function
    async function getResult() {
        var result = await contract.methods.retrieve().call();
        console.log(result);
    }
    
    contract.methods.retrieve().call().then(function (result) {
        // callback function
        console.log(result);
    });
    

    【讨论】:

    • 感谢您的回答,但我仍然无法使用程序无法识别的功能。
    • @TheStudent “程序无法识别”是什么意思?脚本会抛出相同的错误消息还是不同的错误消息(在这种情况下是什么消息)?
    • 脚本返回 main.js:175 Uncaught TypeError: Cannot read property 'retrieve' of undefined at main.js:175
    • @TheStudent 您似乎没有正确实例化var contract。您能检查一下您使用的是 asnswer 定义的大写 Cnew 关键字吗?如果您正确使用它,还要检查地址和 ABI JSON(传递到 new Contract 构造函数)是否有效。
    • 感谢您的帮助。我应用了您的指示,但问题仍然存在,因此我搜索并应用了教程。然后我找到了一个使用 window.nameofcontract 的教程,我不知道它为什么会起作用,但是在它前面使用 window 可以。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 2015-07-21
    • 2018-06-24
    • 2021-10-28
    • 2016-10-16
    相关资源
    最近更新 更多