【问题标题】:Issue with Web3 1.1.0Web3 1.1.0 的问题
【发布时间】:2019-03-19 23:43:53
【问题描述】:

我正在开发一个 React 应用程序,它使用一个将 Web3 作为依赖项的库。我之前可以通过以下代码获取当前的 Metamask 地址:

 const injectedWeb3 = window.web3 || undefined;

 this.state = {
      web3: injectedWeb3
    };

  getAccount() {
    const { web3 } = this.state;
    if (web3.eth.accounts[0]) return web3.eth.accounts[0];
    throw new Error('Your MetaMask is locked. Unlock it to continue.');
  }

然后我将该库更新为最新版本,将其 Web3 依赖项更改为 Web3 1.0 。现在,当我运行完全相同的代码时,出现以下错误:

Error: Invalid JSON RPC response: undefined 
TypeError: e is not a function[Learn More] 

对可能发生的事情有什么想法吗?

【问题讨论】:

    标签: javascript reactjs ethereum web3 metamask


    【解决方案1】:

    我遇到了同样的问题,我用这段代码解决了:

    web3.eth.getAccounts(function (err, accounts) {
          if (err != null) {
            console.log(err)
          }
          else if (accounts.length === 0) {
            console.log('MetaMask is locked');
          }
          else {
            console.log('MetaMask is unlocked'); 
            console.log(accounts[0]);
          }
        });
    

    您还需要添加ethereum.enable();。希望这可以帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-22
      • 2021-05-28
      • 2019-05-24
      • 2021-06-16
      • 2018-07-06
      • 2021-11-29
      • 1970-01-01
      • 2016-07-11
      相关资源
      最近更新 更多