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

React代码报错:undefined is not an object (evaluating 'pray.findIndex')

问题描述

运行以下React代码时出现错误:undefined is not an object (evaluating 'pray.findIndex')

代码如下:

const [pray, setPray] = useState([]);
const fetchPray = async county => {
 const url4 = '-' + county;
 console.log(url4);
 fetch(url4)
.then(response => response.json())
.then(json => setPray(json))
.then(pray => {
  let index = pray.findIndex(d => d.MiladiTarihKisa === date);
  let selectData = pray[index];

  setVakitGunes(selectData.Gunes);
  setVakitImsak(selectData.Imsak);
  setVakitOgle(selectData.Ogle);
  setVakitIkindi(selectData.Ikindi);
  setVakitAksam(selectData.Aksam);
  setVakitYatsi(selectData.Yatsi);
  setGunTurkce(selectData.MiladiTarihUzun);
})
.catch(error => console.log(error))
.finally(() => setLoading4(false));
};
问题原因及解决办法
  • 核心原因:setPray(json)是异步更新状态的操作,且后续.then(pray => { ... })中的pray参数并非更新后的状态值——setPray本身无返回值,所以此处pray为undefined,调用findIndex必然报错。

  • 修复方案:

    1. 直接使用接口返回的json数据处理逻辑,无需依赖异步更新的状态:
      const [pray, setPray] = useState([]);
      const fetchPray = async county => {
       const url4 = '-' + county;
       console.log(url4);
       fetch(url4)
      .then(response => response.json())
      .then(json => {
         setPray(json);
         // 直接用接口返回的json数据处理
         let index = json.findIndex(d => d.MiladiTarihKisa === date);
         // 增加判断,避免匹配不到数据时出现新错误
         if (index !== -1) {
           let selectData = json[index];
           setVakitGunes(selectData.Gunes);
           setVakitImsak(selectData.Imsak);
           setVakitOgle(selectData.Ogle);
           setVakitIkindi(selectData.Ikindi);
           setVakitAksam(selectData.Aksam);
           setVakitYatsi(selectData.Yatsi);
           setGunTurkce(selectData.MiladiTarihUzun);
         }
      })
      .catch(error => console.log(error))
      .finally(() => setLoading4(false));
      };
      
    2. 额外优化:添加index !== -1的判断,防止当date无匹配数据时,selectData为undefined引发新的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 06:45:56