You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中使用await触发ReferenceError问题求助

问题分析与解决方案

你遇到的两个错误都是因为**await的使用规则和代码块范围**的问题,我来一步步给你拆解:

错误原因

  1. ReferenceError: await is not defined:await关键字只能在标记为async的函数内部使用,但你写的那个.then()的回调函数并没有声明为async,所以JS引擎不认识里面的await。
  2. Expression statement is not assignment or call:你的if (responseJson.status === 'success')后面没有加花括号{},这导致下一行的await AsyncStorage.setItem(...)被当成了if语句的“后续独立代码”,而这行代码里的await又不在async函数里,直接触发语法错误。

修复后的代码(两种写法)

写法1:修改原有的.then()回调

把.then()的回调改成async函数,同时给if语句加上花括号,确保代码块范围正确:

async _onPress() {
  NetInfo.isConnected.fetch().then(async (isConnected) => { // 给回调添加async标记
    if (isConnected) {
      fetch(apiURL + '/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          username: this.props.username,
          password: this.props.password
        })
      })
      .then((response) => response.json())
      .then(async (responseJson) => { // 这里必须添加async才能用await
        if (responseJson.status === 'success') { // 加上花括号包裹代码块
          await AsyncStorage.setItem('token', responseJson.token);
          // 跳转到主页面
          Actions.MainScreen();
        } else {
          Toast.show({ text: "Wrong username or password!", type: "danger" });
        }
      })
      .catch((error) => {
        console.log(error);
      });
    } else {
      Toast.show({ text: "Please Connect To Internet", type: "danger" });
    }
  });
}

写法2:改用全await风格(更简洁易读)

既然你的_onPress已经是async函数了,完全可以把所有的.then()都换成await,避免回调嵌套,代码更清晰:

async _onPress() {
  try {
    const isConnected = await NetInfo.isConnected.fetch();
    if (!isConnected) {
      Toast.show({ text: "Please Connect To Internet", type: "danger" });
      return;
    }

    const response = await fetch(apiURL + '/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: this.props.username,
        password: this.props.password
      })
    });

    const responseJson = await response.json();
    if (responseJson.status === 'success') {
      await AsyncStorage.setItem('token', responseJson.token);
      Actions.MainScreen();
    } else {
      Toast.show({ text: "Wrong username or password!", type: "danger" });
    }
  } catch (error) {
    console.log(error);
    Toast.show({ text: "Something went wrong!", type: "danger" });
  }
}

这种写法把所有异步操作都用await处理,并用try/catch统一捕获错误,比嵌套的.then()更易维护,也更符合async/await的设计初衷。

内容的提问来源于stack exchange,提问作者PuskarShestha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:12:19