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

React Native新手求助:fetch返回Promise时出现“Undefined is not an object”错误

解决"Undefined is not an object"错误:正确返回fetch的Promise

我瞅了下你的代码,问题出在onVerify函数没有返回整个fetch的Promise链,导致你在step()里调用onVerify().then()时,实际上是在undefined上调用.then()方法——这就是你看到的错误根源。

问题分析

fetch本身返回Promise,但你的onVerify函数执行完后默认返回undefined(因为没有显式return)。当你尝试在undefined上调用.then(),JS就会抛出"Undefined is not an object"的错误。另外你原代码的语法也有缺失的闭合括号/大括号,这也可能导致意外的运行问题。

修复步骤

  1. 在onVerify里,要把整个fetch()调用的Promise链return出去,这样外部才能用.then()接收返回的responseJson。
  2. 补全代码里缺失的语法闭合部分,保证代码结构完整。
  3. 优化请求体的写法,用模板字符串替代字符串拼接,更清晰也不容易出错。

修正后的代码

auth.js

import { Alert } from 'react-native'; // 别忘了导入Alert组件!

export const onVerify = (email, password, navigation) => {
  console.log('Verifying');
  // 关键:return整个fetch的Promise链
  return fetch('xxx', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    // 用模板字符串优化请求体拼接
    body: `email=${email}&password=${password}`
  })
  .then((response) => response.json())
  .then((responseJson) => {
    if(responseJson.status == '200') {
      Alert.alert(
        'Login Successful',
        'Welcome Home'
      );
      let data = {
        name: responseJson.name,
        id : responseJson.id
      };
      onSignIn(); // 假设onSignIn是你已定义好的函数
      return responseJson; // 把数据返回给后续的.then
    }
    // 处理登录失败的情况,返回rejected状态的Promise
    return Promise.reject(new Error('Login failed: incorrect status'));
  })
  .catch((error) => {
    // 捕获网络请求或JSON解析的错误
    console.error('Verification error:', error);
    return Promise.reject(error);
  });
};

signin.js

export default class SignIn extends React.Component{
  step(){
    onVerify(this.state.email, this.state.password, this.props.navigation)
    .then((data) => { // 用箭头函数避免this指向问题
      console.log(data); // 现在这里能拿到正确的responseJson数据了
    })
    .catch((error) => {
      // 统一处理错误,比如弹窗提示用户
      Alert.alert('Login Error', error.message);
    });
  }
}

额外提示

  • 永远不要忽略Promise的catch分支,不然网络错误、接口报错等问题会静默失败,很难排查。
  • 如果onSignIn是异步函数,记得要等它执行完成后再返回数据,比如把onVerify改成async函数,用await onSignIn();等待它完成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:15:51