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

React Native Fetch API处理Promise返回undefined如何获取token

问题根因

代码拿不到响应数据的核心错误在Promise链的返回值处理:

  • response.json()是异步方法,返回值是Promise对象,你在第一个.then()回调里只打印了这个Promise对象,没有把结果返回给Promise链的下一环,第二个.then()接收到的参数自然是undefined。
  • 额外注意:Fetch API只有网络层面的错误(断网、域名无法解析等)才会触发catch,接口返回400、401、500这类业务错误状态码时,依然会进入then分支,不做状态校验直接解析数据很容易出现逻辑异常。
修正方案

推荐用更易读的async/await写法实现,本地存储token可以使用React Native生态通用的@react-native-async-storage/async-storage库,先执行npm i @react-native-async-storage/async-storage安装依赖后,按如下逻辑编写代码:

import AsyncStorage from '@react-native-async-storage/async-storage';

// 登录请求逻辑
const loginRequest = async () => {
  try {
    const response = await fetch(loginURL, {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        user_name: email,
        password: password,
      })
    });

    // 先校验HTTP状态是否正常
    if (!response.ok) {
      const errInfo = await response.json();
      // 在这里处理登录失败逻辑,比如提示账号密码错误
      throw new Error(errInfo?.message || '登录请求失败');
    }

    // 解析响应体JSON
    const resData = await response.json();
    console.log('接口返回完整数据:', resData);

    // 提取token存储到本地
    if (resData.token) {
      await AsyncStorage.setItem('local_user_token', resData.token);
      // 存储完成后可以写登录成功后的跳转、状态更新逻辑
    }
  } catch (error) {
    console.log('请求异常:', error);
    // 统一处理错误提示
  }
}

如果你更习惯用原来的then链式写法,只需要补全返回值、加上状态校验即可:

fetch(loginURL, {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    user_name: email,
    password: password,
  })
})
.then((response) => {
  if (!response.ok) {
    return response.json().then(err => { throw new Error(err.message || '登录失败') });
  }
  // 关键:必须把解析后的Promise返回给下一环then
  return response.json();
})
.then(async (data) => {
  console.log('解析后的响应数据:', data);
  if (data.token) {
    await AsyncStorage.setItem('local_user_token', data.token);
  }
})
.catch((error) => console.log(error))
补充说明
  • Promise链式调用中,只要需要在下一个then拿到上一步的处理结果,就必须在当前then的回调中return对应的值,否则下一环接收到的参数永远是undefined
  • 如果你的应用对安全要求较高,不建议明文存储token,可以替换为react-native-keychain这类支持加密存储的库,降低token泄露风险

内容的提问来源于stack exchange,提问作者Karar Al-Mamaar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 06:39:23