简体   繁体   中英

Web3 metamask connection Cannot read properties of undefined (reading 'ethereum')

I have a react application in which I am trying to connect to metamask extension via web3. In my thunk.ts , I am calling the required functions but I am getting a type error that I cannot read the properties of undefined(reading 'ethereum'). Here is the code that I am using



if (window.ethereum) {//the error line
      window.web3 = new Web3(window.ethereum);

    try {
      await window.ethereum.enable();

      updateAddress(dispatch);
    } catch (err) {
      alert("Something went wrong.");
    }
  } else if (window.web3) {
    window.web3 = new Web3(window.web3.currentProvider);
    updateAddress(dispatch);
  } else {
    alert("You have to install MetaMask !");
  }
};

Here is the error screenshot
这是错误截图

I solved it by using the following code

declare global {
  interface Window {
    ethereum?: any;
    web3?:any
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM