1

我正在开发一个使用具有 Web3 作为依赖项的库的 React 应用程序。我以前可以使用以下代码获取当前的 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] 

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

4

1 回答 1

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]);
      }
    });

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

于 2019-08-20T13:59:24.920 回答