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验证。
- 使用axios时,若导入方式错误会导致库实例为undefined:
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));
快速验证方案
- 先发送极简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)); - 请求前打印关键变量:
console.log(postURL, formData, typeof fetch),确认无undefined值。
内容的提问来源于stack exchange,提问作者MVC Developer Team
相关产品推荐
相关产品推荐

