开发者问题收集

未捕获的 TypeError:web3 不是构造函数。区块链网站无法连接到 metamask

2022-04-11
6308

我在 web3.eth.defaultAccount = web3.eth.getAccounts();

下面是代码。它说 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'getAccounts')

我的 web3 版本是“^1.3”。

var contract = "";

if (typeof web3 !== 'undefined') {
console.log('inside web3')
Web3 = new Web3 (Web3.currentProvider);
} else {
console.log('else web3');
var web3 = new Web3(new Web3.providers.HttpProvider(provider));

}

window.ethereum.enable()
.then(function (accounts) {
    console.log(accounts[0]);

    web3.eth.defaultAccount = web3.eth.getAccounts();

    var contractabi = web3.eth.contract([ABI])
2个回答

函数必须是异步的

window.addEventListener("load", async () => {
  // Modern dapp browsers...
  if (window.ethereum) {
    const web3 = new Web3(window.ethereum);
    try {
      // Request account access if needed
      await window.ethereum.enable();
      // Acccounts now exposed
      resolve(web3);
    } catch (error) {
      reject(error);
    }
  }

尝试一下以适合您的情况

Sai Kiran
2022-04-11

如果可能的话,请将此代码的完整实现发送给我,或者您可以添加此

class App extends Component {
  async UNSAFE_componentWillMount() {
    await this.loadWeb3();
    await this.loadBlockchainData();
  }

  async loadWeb3() {
    if (window.ethereum) {
      window.web3 = new Web3(window.ethereum);
      await window.ethereum.enable();
    } else if (window.web3) {
      window.web3 = new Web3(window.web3.currentProvider);
    } else {
      window.alert('No ethereum broswer detected! You can check out MetaMask!');
    }
  }

  async loadBlockchainData() {
    const web3 = window.web3;
    const account = await web3.eth.getAccounts();
    this.setState({ account: account[0] });
    const networkId = await web3.eth.net.getId();
  }
}

请使用异步函数与 web3 交互并等待响应

Sai Kiran
2022-04-12