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

React Native发送POST请求时出现'undefined is not a function'错误求助

问题定位与解决方案

常见触发原因及排查步骤

  • 请求方法调用错误
    这是最常见的诱因:

    • 误将fetch或第三方请求库(如axios)的调用方式写错,比如省略调用括号(fetch.then()而非fetch(url).then())
    • 调用了FormData不存在的方法,比如用Web端的set/delete替代React Native仅支持的append
      示例错误代码:
    // 错误:fetch未执行调用,直接引用函数本身
    fetch.then(res => res.json())
    // 正确写法
    fetch(postURL, options).then(res => res.json())
    
  • 依赖库导入/初始化异常

    • 使用axios时,若导入方式错误会导致库实例为undefined:
      // 错误导入
      import { axios } from 'axios';
      // 正确导入
      import axios from 'axios';
      
    • React Native内置fetch无需导入,但部分旧版本存在兼容性问题,可临时替换为axios验证。
  • FormData使用不符合RN规范
    React Native的FormData与Web端有差异,需注意:

    • 必须通过new FormData()实例化,不能直接字面量创建
    • 仅支持append方法添加字段,文件类型需传入包含uri/name/type的对象
      示例正确用法:
    const formData = new FormData();
    formData.append('fieldName', 'fieldValue');
    formData.append('attachment', {
      uri: localFileUri,
      name: 'document.pdf',
      type: 'application/pdf'
    });
    
  • 请求配置结构错误
    确保fetch/axios的配置对象格式正确,关键属性(method/headers/body)不能缺失或位置错误:

    // 正确的fetch POST配置
    fetch(postURL, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        // 若用FormData,无需手动设置Content-Type,RN会自动添加边界标识
      },
      body: formData
    })
    .then(res => res.json())
    .catch(error => console.error('请求失败:', error));
    

快速验证方案

  1. 先发送极简JSON请求,排除FormData干扰:
    fetch(postURL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ test: 'demo' })
    })
    .then(res => res.json())
    .catch(err => console.error(err));
    
  2. 请求前打印关键变量:console.log(postURL, formData, typeof fetch),确认无undefined值。

内容的提问来源于stack exchange,提问作者MVC Developer Team

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 19:05:19