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

React Native Expo启动时JSON.parse: Unexpected EOF错误求助

问题根源分析及修复方案

核心问题

关闭重启应用时触发的JSON.parse: Unexpected EOF,本质是组件初始化阶段labelsReference还未通过异步请求获取到有效数据,此时它是初始空值/无效值,直接调用JSON.parse就会报错。

你的代码存在几个关键问题:

  1. useEffect里对res.json()的结果重复调用JSON.parse——res.json()已经将响应体解析为JS对象,不需要再二次解析。
  2. setEventLabelsReference的参数写错了,你用了labelsReference(状态变量)而非刚获取到的eventLabelsReference。
  3. getEventLabel没有做空值校验,在labelsReference未初始化完成时就执行解析操作。

修复步骤及代码示例

1. 修正useEffect中的请求逻辑

useEffect(() => {
  getData().then((value) => {
    fetch(`${MY_API}/home/${value?.username}`, {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
    })
    .catch((e) => console.log(e))
    .then(async (res) => {
      // res.json()已经返回解析后的JS对象,无需再JSON.parse
      const response = await res.json();
      // 直接取response里的labels_reference,它已经是数组格式
      const eventLabelsReference = response.labels_reference;
      // 直接设置状态,不需要再parse
      setEventLabelsReference(eventLabelsReference);
      setResponse(response);
    });
  });
}, [navigation]);

2. 给labelsReference设置合理初始值

假设你用useState声明状态,初始值设为空数组:

const [eventLabelsReference, setEventLabelsReference] = useState([]);

3. 给getEventLabel增加空值校验和安全访问

const getEventLabel = (pk) => {
  // 先判断是否有有效数据,避免parse空值
  if (!eventLabelsReference || eventLabelsReference.length === 0) {
    return '默认标签'; // 或者返回你需要的默认值
  }
  // 因为已经直接存了数组,不需要再JSON.parse
  const event_label = eventLabelsReference.find(item => item.pk == pk);
  // 增加空值判断,避免找不到对应pk时访问title报错
  return event_label?.title || '未知标签';
};

为什么之前的临时操作有效?

  • 注释getEventLabel内的代码返回'test'时,跳过了对未初始化的labelsReference的解析操作,所以不会触发错误。
  • 恢复代码后,此时异步请求已经完成,labelsReference已经有了有效数据,所以解析正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 12:57:21