【问题标题】:What To Do Failed Compiling?编译失败怎么办?
【发布时间】:2021-10-22 04:49:07
【问题描述】:

运行命令 NPM Start 时出现错误。该文件是在 PanCakeSwap 前端创建的,我已经尝试修复了一段时间,感谢您的帮助:)

这是我的 App.js 代码:

import React, { useState, useEffect  } from "react";
import SimpleStorageContract from "./contracts/SimpleStorage.json";
import getWeb3 from "./getWeb3";
import BlockchainContext from './BlockchainContext.js';

import "./App.css";

function App() {
    const [storageValue, setStorageValue] = useState(undefined);
    const [web3, setWeb3] = useState(undefined);
    const [accounts, setAccounts] = useState([]);
    const [contract, setContract] = useState([]);

    useEffect(() => {
        try {
              // Get network provider and web3 instance.
               const web3 = await getWeb3();
        
        //             // Use web3 to get the user's accounts.
                           const accounts = await web3.eth.getAccounts();
        
        //                         // Get the contract instance.
                                       const networkId = await web3.eth.net.getId();
                                             const deployedNetwork = SimpleStorageContract.networks[networkId];
                                                   const contract  = new web3.eth.Contract(
                                                           SimpleStorageContract.abi,
                                                                   deployedNetwork && deployedNetwork.address,
                                                                         );
        
                                                                               // Set web3, accounts, and contract to the state, and then proceed with an                                                             // example of interacting with the contract's methods.
                 
            setWeb3(web3);
            setAccounts(accounts);
            setContract(contract);;
            
            this.setState({ web3, accounts, contract: instance                       } catch (error) {
                                                                        // Catch any errors for any of the above operations.
                                                                       alert(
                                                                      `Failed to load web3, accounts, or contract. Check console for details.`,
                                                                                                                         );
                                                                                                                               console.error(error);
        
        const init = async() => {
        }
        init();
    }, []);

    useEffect(() => {
            const load = async () => {
            // Stores a given value, 5 by default.
             await contract.methods.set(5).send({ from: accounts[0] });
        
        //         // Get the value from the contract to prove it worked.
                     const response = await contract.methods.get().call();
        
        //                 // Update state with the result.
                     setStorageValue(response);       
        }
        if(typeof web3 !== 'undefined'
            && typeof account !== 'undefined'
            && typeof contract !== 'undefined'{
            load();
            }
    }, [web3, accounts, contract]);

    if(typeof web3 === 'undefined') {
    return <div>Loading Web3, account, and contract...</div>;
    }

      return (
                <div className="App">
          <BlockchainContext.Provider value={{web3, accounts, contract}}>
                  <h1>Good to Go!</h1>
                  <p>Your Truffle Box is installed and ready.</p>
                  <h2>Smart Contract Example</h2>
                  <p>
                    If your contracts compiled and migrated successfully, below will show
                    a stored value of 5 (by default).
                  </p>
                  <p>
                    Try changing the value stored on <strong>line 42</strong> of App.js.
                  </p>
                  <div>The stored value is: {storageValue}</div>
          </BlockchainContext.Provider>
                </div>
              );

}

export default App;

我得到的错误是: ** 编译失败。

./src/App.js 第 17:23 行:解析错误:不能在异步函数之外使用关键字 'await'

15 |尝试 { 16 | // 获取网络提供者和 web3 实例。

17 |常量 web3 = 等待 getWeb3(); | ^ 18 |
19 | // // 使用 web3 获取用户的帐号。 20 |常量帐户 = 等待 web3.eth.getAccounts(); **

【问题讨论】:

  • 你需要查看 js 中的 async-await 来解决它,而且你的代码看起来真的很不干净,它让那里的东西理解起来很复杂。

标签: node.js typescript fork truffle npm-start


【解决方案1】:

提供的代码非常混乱,但看起来您正试图在同步函数中使用await 关键字,特别是作为参数传递给useEffect() 的函数。 await 关键字只能在 asynchronous functions 内部使用。
如果可以,最简单的解决方案是通过添加 async 关键字使函数异步(如下所示)。

function App() {
    const [storageValue, setStorageValue] = useState(undefined);
    const [web3, setWeb3] = useState(undefined);
    const [accounts, setAccounts] = useState([]);
    const [contract, setContract] = useState([]);

    useEffect(async () => {

如果这不起作用,您可以改用.then()(如下所示),但这需要更多工作。

function App() {
    const [storageValue, setStorageValue] = useState(undefined);
    const [web3, setWeb3] = useState(undefined);
    const [accounts, setAccounts] = useState([]);
    const [contract, setContract] = useState([]);

    useEffect(() => {
        try {
              // Get network provider and web3 instance.
               getWeb3().then(web3=>{
                  // code goes here
               }).catch(err=>{
                  // error handling
               });        

如果您还没有阅读,我还建议您阅读一些关于 async/await 的内容。 This MDN article 是一个很好的起点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-20
    • 2011-04-26
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    • 2014-05-14
    • 2011-09-03
    • 2019-02-10
    相关资源
    最近更新 更多