我使用的是nextjs + reactjs + typescript。没有typescript是完美的,但当使用typescript时,我得到了这个错误。顺便说一句,我在这里使用的是useMemo,但我尝试在函数外部初始化它。在这两种情况下,我都得到了相同的错误。
下面是我目前正在使用的代码片段
const INFURA_ID = process.env.REACT_APP_INFURA_ID;
const initWeb3 = (provider: any) => {
const web3 = new Web3(provider);
web3.eth.extend({
methods: [
{
name: "chainId",
call: "eth_chainId",
outputFormatter: web3.utils.hexToNumber as any,
},
],
});
return web3;
};
export function Web3UtilityProvider() {
const [walletAddress, setWalletAddress] = useState(null);
const { user, authDispatch } = useAuth();
const dAppClient = useMemo(() => new DAppClient({ name: "Beacon Docs" }), []);
const web3Modal = useMemo(() => {
return new Web3Modal({
// network: "mainnet", // optional
cacheProvider: true, // optional
providerOptions: {
walletconnect: {
package: WalletConnectProvider, // required
options: {
infuraId: INFURA_ID,
},
},
// torus: {
// package: Torus,
// },
fortmatic: {
package: Fortmatic,
options: {
key: process.env.REACT_APP_FORTMATIC_KEY,
},
},
authereum: {
package: Authereum,
},
bitski: {
package: Bitski,
options: {
clientId: process.env.REACT_APP_BITSKI_CLIENT_ID,
callbackUrl:
window.location.href + "bitski-callback.html",
},
},
},
});
}, []);
const logoutOfWeb3Modal = useCallback(async () => {
async () => {
web3Modal.clearCachedProvider();
setTimeout(() => {
typeof window !== "undefined" && window.location.reload();
}, 1);
};
}, [web3Modal]);
const loadWeb3Modal = useCallback(async () => {
const provider = await web3Modal.connect();
if (!provider?.on) {
return;
}
const web3 = initWeb3(provider);
const accounts = await web3.eth.getAccounts();
provider.on("close", () => {
logoutOfWeb3Modal();
});
provider.on("accountsChanged", async (accounts: any) => {
console.log("accountsChanged", accounts);
if (!accounts || !accounts.length) {
return;
}
});
}, []);
return (
<Web3Context.Provider
value={{
logoutOfWeb3Modal,
loadWeb3Modal
}}
>
{children}
</Web3Context.Provider>
);
}

发布于 2021-10-29 07:04:12
实际上,这个错误与js或ts无关;由于CSR,它使用的是reactjs应用程序,但在我的例子中,我使用的是nextjs,而由于SSR,该窗口对象没有定义。因此,为了解决这个错误,我简单地使用了回退(即useEffect)。
https://stackoverflow.com/questions/69742413
复制相似问题