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

使用JavaScript调用智能合约函数时出现未定义问题及web3实例化相关报错求助

Hey there! No worries at all—we all start somewhere with Web3 and JavaScript. Let's break down your issues one by one and fix them up.

1. Fixing Web3 Initialization & getAccounts() Error

First, let's tweak your Web3 initialization code and address the async issue with getAccounts():

Your Initialization Tweaks

Your existing code has a small typo in the fallback branch (App.web3Provider should be the web3Provider variable you just defined). Plus, modern Web3.js (v1.x) has a more reliable initialization pattern that accounts for MetaMask's current API:

let web3;

// Modern dapp browsers (like MetaMask)
if (window.ethereum) {
  web3 = new Web3(window.ethereum);
  try {
    // Request user permission to access their accounts
    await window.ethereum.enable();
  } catch (err) {
    console.error("User denied account access:", err);
  }
}
// Legacy dapp browsers
else if (window.web3) {
  web3 = new Web3(window.web3.currentProvider);
}
// Fallback to local Ganache node
else {
  const provider = new Web3.providers.HttpProvider('http://localhost:7545');
  web3 = new Web3(provider);
}

Fixing the getAccounts() Error

web3.eth.getAccounts() is an asynchronous function—it returns a Promise, not the direct account list. Your error comes from trying to log it like a synchronous value. Use either .then() chaining or async/await to handle it properly:

// Using .then()
web3.eth.getAccounts()
  .then(accounts => {
    console.log("Connected accounts:", accounts);
    // Set default account if needed
    web3.eth.defaultAccount = accounts[0];
  })
  .catch(err => console.error("Failed to get accounts:", err));

// Or using async/await (inside an async function)
async function fetchAccounts() {
  try {
    const accounts = await web3.eth.getAccounts();
    console.log("Connected accounts:", accounts);
    web3.eth.defaultAccount = accounts[0];
  } catch (err) {
    console.error("Failed to get accounts:", err);
  }
}
fetchAccounts();

2. Fixing the Cannot read properties of undefined (reading 'addFood') Error

This error means your contract object isn't properly initialized—Web3 can't find the addFood method because the contract instance wasn't set up correctly. Here's how to fix it:

Step 1: Properly Instantiate Your Contract

To interact with a Solidity contract, you need two things:

  • The contract's ABI (Application Binary Interface, generated when you compile the contract)
  • The contract's deployed address

Use these to create a valid contract instance:

// Replace with your actual contract ABI and deployed address
const foodContractABI = [/* Paste your contract's ABI here */];
const foodContractAddress = "0xYourDeployedContractAddress";

// Create the contract instance
const contract = new web3.eth.Contract(foodContractABI, foodContractAddress);

Step 2: Call addFood Correctly

Make sure you've fetched the user's account before calling the contract method, and use Web3's event handlers to track the transaction:

// Wrap this in an async function or use .then() as shown earlier
async function submitFood() {
  try {
    const accounts = await web3.eth.getAccounts();
    const eth_pk = document.getElementById("pk").value;
    const eth_fd = document.getElementById("fd").value;
    const eth_pl = document.getElementById("pl").value;
    const eth_prc = document.getElementById("prc").value;

    // Execute the contract method
    await contract.methods.addFood(eth_pk, eth_fd, eth_pl, eth_prc)
      .send({ from: accounts[0] })
      .on('transactionHash', hash => console.log("Transaction hash:", hash))
      .on('receipt', receipt => console.log("Transaction confirmed:", receipt))
      .on('error', err => console.error("Transaction failed:", err));
  } catch (err) {
    console.error("Error submitting food:", err);
  }
}

Double-check that your Solidity contract actually has an addFood function, and that your ABI includes this method (missing ABI entries are a common cause of this error).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 16:47:26