【问题标题】:How to solve error: Can not use keyword 'await' outside an async function in React如何解决错误:不能在 React 的异步函数之外使用关键字 'await'
【发布时间】:2021-08-12 14:10:04
【问题描述】:

我想从该设备动态获取 IP 地址(因为它会超时更改),然后使用来自 node.js 服务器的 fetch:https://{ipadress}:5000/users 中的链接从数据库中获取 JSON。但现在它给了我一个错误 Can not use keyword 'await' outside an async function。我不知道如何解决它。 函数publicIP() 是问题所在。

async componentDidMount() {
            this.drawOnCanvas();
            var ipAdress = '';
            publicIP()
            .then(ip => {    
                console.log(ip);
                const url = "http://" + ip + ":5000/user";
                const response = await fetch(url);
                const data = await response.json(); 
                this.setState({userData: data});
                console.log(this.state.userData);
            // '47.122.71.234'
            })
            .catch(error => {
            console.log(error);
            // 'Unable to get IP address.'
            });
           

【问题讨论】:

    标签: node.js reactjs react-native async-await


    【解决方案1】:

    您不应将async/await.then().catch() 混用。选择你更喜欢的一个并坚持下去。所以在你的情况下你应该这样做

    componentDidMount() {
      this.drawOnCanvas();
      var ipAdress = '';
      return publicIP()
        .then(ip => {    
          console.log(ip);
          const url = "http://" + ip + ":5000/user";
          return fetch(url);
        })
        .then(res => {
          return res.json();
        })
        .then(data => {
          this.setState({userData: data});
          console.log(this.state.userData);            
        })
        .catch(error => {
           console.log(error);
        });
    }
    

    async componentDidMount() {
      try {
        this.drawOnCanvas();
        var ipAdress = '';
        const ip = await publicIP()
        console.log(ip);
        const url = "http://" + ip + ":5000/user";
        const response = await fetch(url);
        const data = await response.json(); 
        this.setState({userData: data});
        console.log(this.state.userData);
      } catch (error) {
        console.log(error);
      }
    }
    

    【讨论】:

    • 在第一个代码示例中,是否需要publicIP() 之前的return?!
    • @Yousaf 取决于。如果发生反应 componentDidMount() 可能不会(我对反应不是很熟悉,所以我在这里可能错了)。在一般情况下,如果您希望某个方法 xy() 成为承诺链的一部分,是的,因为否则这不会等待承诺解决/拒绝
    • componentDidMount 是生命周期方法,这里不需要return
    【解决方案2】:

    试试这样:

    async componentDidMount() {
        this.drawOnCanvas();
        try
        {
            var ip = await publicIP();
            console.log(ip);
    
            const url = "http://" + ip + ":5000/user";
            const response = await fetch(url);
            const data = await response.json(); 
            this.setState({userData: data});
            console.log(this.state.userData);  // '47.122.71.234'
        } catch(error) {
            console.log(error);  // 'Unable to get IP address.'
        }
    }
    

    另外我认为你应该使用async/await.then/.catch,但不要混合使用。

    【讨论】:

    • 谢谢!有效。出于某种原因,我得到了错误的 ip,这与我输入命令提示符 ipconfig 并转到 ipv4 时不同。任何想法来获得正确的IP?所以我可以拿它
    • 您似乎想在本地机器上调用端点,对吧?那么为什么不能只使用固定值127.0.0.1localhost 作为ip
    • 好吧,我也想从其他计算机连接到这个应用程序。因此,我需要运行 React 应用程序的计算机的本地 IP。这样其他电脑也可以获取json数据
    • 好的,但是其他计算机应该如何知道运行您的 React 应用程序的主机的 IP 地址?我认为您必须对消费者中的地址进行硬编码或进行一些路由(例如编辑 hosts 配置以将 IP 地址映射到 dns 名称)。
    • 据我所知,React 只是一种客户端技术。所以你在想要使用这个前端的机器上启动一个本地服务器。该服务器只为前端提供 JS 和 HTML 文件。这里不涉及后端服务。如果您想调用后端来获取一些数据,您还需要后端技术(NodeJS、Java 等)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 2017-02-02
    • 1970-01-01
    相关资源
    最近更新 更多