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

React Native中fetch获取JSON数据执行map操作报undefined错误如何解决

问题根因

你遇到的undefined is not an object (evaluating 'json.map')报错核心原因是:
第一个.then回调中执行response.json()后没有添加return语句,导致链式调用的下一个.then拿到的json参数是undefined,自然不存在map方法。

修复方案

1 基础修复(仅解决当前报错)

在response.json()前增加return即可,额外加一层数组类型判断可以避免后续接口结构变动引发的同类问题:

CheckifReadLater = async () => {
    const username = await AsyncStorage.getItem('username');
    const isLoggedIn = await AsyncStorage.getItem('isLoggedIn');
    if (isLoggedIn == 1 && username) {
      await fetch(Config.backendAPI+`/readlater.php?username=${username}&select`)
        .then((response) => {
          reactotron.log("Response : ",response);
          return response.json(); // 新增return语句
        })
        .then((json) => {
          // 新增数组类型判断
          if(Array.isArray(json)){
            json.map((product, index) => {
              if (product.id == this.props.product.id) {
                this.setState({
                  isReadLater: true,
                })
              }
            });
          }
        })
        .catch((error) => reactotron.log('This is the error: ',error))
    }
    reactotron.log("Readlater : ",this.state.isReadLater);
}

2 优化版(统一语法、提升性能)

既然已经使用了async/await语法,就没必要混用.then链式调用,同时用Array.some()替代map可以在匹配到目标项后提前终止遍历,减少不必要的性能消耗:

CheckifReadLater = async () => {
  try {
    const username = await AsyncStorage.getItem('username');
    const isLoggedIn = await AsyncStorage.getItem('isLoggedIn');
    if (isLoggedIn == 1 && username) {
      const response = await fetch(Config.backendAPI+`/readlater.php?username=${username}&select`);
      reactotron.log("Response : ",response);
      const json = await response.json();
      if(Array.isArray(json)){
        const hasMatch = json.some(product => product.id == this.props.product.id);
        if(hasMatch){
          this.setState({
            isReadLater: true
          })
        }
      }
    }
    reactotron.log("Readlater : ",this.state.isReadLater);
  } catch (error) {
    reactotron.log('This is the error: ',error)
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 05:45:00