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

React+TypeScript项目中Axios调用MobyGames API无返回结果求助

解决React+TypeScript调用MobyGames API无结果且报错的问题

问题分析与修复步骤

1. 修复useEffect无限循环问题

你的useEffect未添加依赖数组,会导致组件每次渲染都重复发送请求,触发浏览器请求限制或异常。添加空依赖数组让请求仅在组件挂载时执行一次:

useEffect(() => {
  apiClient
    .get<FetchGameResponse>("/games")
    .then((response) => {
      console.log(response.data.games);
      setGames(response.data.games); // 更新状态以渲染数据
    })
    .catch((error) => {
      console.error("请求详情:", error); // 打印完整错误信息便于排查
      setError(error.response?.data?.error || error.message || "未知错误");
    });
}, []); // 空依赖数组限制请求仅执行一次

2. 修正API返回类型定义

MobyGames V1 API的/games端点返回结构和你定义的类型不匹配,比如游戏ID字段为game_id而非gameID,且description并非默认返回字段。调整类型定义匹配实际返回:

interface Game {
  game_id: number;
  title: string;
  description?: string; // 需指定额外参数才返回,设为可选
}

interface FetchGameResponse {
  games: Game[];
  total?: number; // API会返回总条数,可选添加
}

3. 完善错误排查逻辑

原代码仅捕获错误消息,无法定位具体问题(如API密钥无效、权限不足、网络问题)。修改catch块打印完整错误对象,包括响应状态码和API返回的错误详情:

.catch((error) => {
  console.error("请求失败详情:", {
    message: error.message,
    status: error.response?.status,
    data: error.response?.data,
    config: error.config
  });
  setError(error.response?.data?.error || error.message || "请求失败");
});

4. 确保状态更新

原代码未调用setGames更新状态,即使请求成功页面也不会渲染数据,需在then回调中添加状态更新逻辑(已包含在第一步代码中)。

额外检查项

  • 确认你的API密钥API_KEY有效,且未超过MobyGames API的请求频率限制
  • 若需要获取description字段,需在请求中添加fields=description参数:
    apiClient.get<FetchGameResponse>("/games", {
      params: { fields: "description" }
    })
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 14:18:26