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

React中fetch API后出现Uncaught ReferenceError: data is not defined错误求助

解决React中Uncaught ReferenceError: data is not defined错误

错误原因

  1. data是fetch回调函数的局部变量,你在回调外部调用setGamesList(data.map(...)),外部根本访问不到这个data,所以触发未定义错误。
  2. fetch是异步操作,就算能访问data,此时请求还未完成,data也没有实际返回值,后续逻辑同样会出错。

修正方案1:在回调内处理数据

把setGamesList放到then回调里,确保能拿到请求返回的data:

const [games, setGAMES] = React.useState([]);
const [gamesList, setGamesList] = React.useState([]);

React.useEffect(() => {
  const options = {
    method: 'GET',
    headers: {
      'X-RapidAPI-Key': '68cd3db2f1mshf35a2b8ae04ad85p1fc5a1jsn0f05ed6a893a',
      'X-RapidAPI-Host': 'free-to-play-games-database.p.rapidapi.com'
    }
  };

  fetch('https://free-to-play-games-database.p.rapidapi.com/api/filter?tag=3d.mmorpg.fantasy.pvp&platform=pc', options)
    .then(response => response.json())
    .then(data => {
      setGAMES(data);
      // 在这里处理data生成gamesList
      setGamesList(data.map(object => ({
        name: object.title,
        link: object.game_url,
      })));
    })
    .catch(err => console.error('请求出错:', err)); // 加上错误捕获,方便排查问题
}, []);

优化方案:去掉冗余状态

gamesList是从games派生出来的,完全不需要单独存成状态,直接在渲染时计算即可,减少不必要的状态更新:

const [games, setGAMES] = React.useState([]);

React.useEffect(() => {
  const options = {
    method: 'GET',
    headers: {
      'X-RapidAPI-Key': '68cd3db2f1mshf35a2b8ae04ad85p1fc5a1jsn0f05ed6a893a',
      'X-RapidAPI-Host': 'free-to-play-games-database.p.rapidapi.com'
    }
  };

  fetch('https://free-to-play-games-database.p.rapidapi.com/api/filter?tag=3d.mmorpg.fantasy.pvp&platform=pc', options)
    .then(response => response.json())
    .then(data => setGAMES(data))
    .catch(err => console.error('请求出错:', err));
}, []);

// 直接在组件内生成gamesList,无需额外状态
const gamesList = games.map(object => ({
  name: object.title,
  link: object.game_url,
}));

内容的提问来源于stack exchange,提问作者Mohamed Amine Hachemi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 12:02:16