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

React-Native发起PATCH请求时遇ENOENT及JSON解析错误求助

解决React Native PATCH请求的两类错误

一、修复SyntaxError: JSON Parse error: Unexpected end of input

这个错误核心原因是服务器返回响应体为空(比如204 No Content状态),但代码强制调用response.json()解析空内容。你的swapShifts函数发起PATCH请求时传入空payload,很多后端处理这类确认型请求会返回204状态且无响应体,此时解析JSON必然失败。

修复代码:

修改patchFetch函数,先判断响应状态再处理解析:

export async function patchFetch(url: string, payload: any, credentials?: string | null) {
    const headers: { [key: string]: string } = {
        'Content-Type': 'application/json',
        // 注:Access-Control-Allow-Origin是后端响应头,前端请求添加无效,直接删除
    };

    if (credentials) {
        headers['Authorization'] = `Basic ${credentials}`;
    }

    const response = await fetch(url, {
        method: 'PATCH',
        headers: headers,
        body: JSON.stringify(payload),
    });

    // 按状态码分情况处理
    if (response.status === 200) {
        return await response.json();
    } else if (response.status === 204) {
        // 204无响应体,直接返回空值
        return null;
    } else if (response.status === 400) {
        throw new Error("Bad Request");
    } else if (response.status === 401) {
        throw new Error("Unauthorized");
    } else if (response.status === 403) {
        throw new Error("Forbidden");
    } else {
        throw new Error("Something went wrong");
    }
}

二、修复ENOENT找不到InternalBytecode.js的错误

这个错误属于Hermes引擎构建缓存或文件缺失问题,按以下步骤解决:

  • 清理React Native缓存:
    在项目根目录执行:
    npx react-native start --reset-cache
    
  • 清理Android构建缓存:
    进入项目android目录执行:
    ./gradlew clean
    
  • 重新构建项目:
    缓存清理完成后,重新运行项目:
    npx react-native run-android
    
  • 检查Hermes配置(可选):
    确认android/app/build.gradle中Hermes配置正确:
    project.ext.react = [
        enableHermes: true,  // 若项目无需Hermes,可设为false后重新构建
    ]
    

额外优化建议

在acceptShift函数中添加错误捕获,避免未处理的Promise异常:

const acceptShift = () => {
    if (selectedShift) {
        swapShifts(selectedShift.id, credentials)
            .then(() => {
                setModalVisible(false);
                setSelectedShift(null);
            })
            .catch((err) => {
                console.error("接受班次失败:", err);
                alert(err.message);
            });
    }
};

内容的提问来源于stack exchange,提问作者Mert Batuhan ÜNVERDİ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:02:44