React中Fetch API触发429请求过多错误的解决方法
修复重复API请求导致的429错误问题
问题核心是组件每次渲染时都会执行顶层的fetchUrl(prop.link)——不管prop.link有没有变化,只要组件因props更新、state变化触发重新渲染,就会发起新请求,最终触发服务端的限流机制(429错误)。
修复方案:用useEffect控制请求时机
React的useEffect钩子可以将API请求这类副作用与组件渲染周期解耦,只在指定依赖项变化时执行请求。
具体修改步骤:
- 导入
useEffect(和useState一起) - 将
fetchUrl的调用移到useEffect内部,指定prop.link为依赖项——仅当link变化时才重新发起请求 - 优化loading状态逻辑,请求开始时重置状态避免旧内容残留
- 可选:添加请求取消逻辑,防止组件卸载后执行state更新引发警告
修改后的完整代码
import { useState, useEffect } from 'react'; function App(prop) { const [content, setContent] = useState([]); const [loading, setLoading] = useState(false); const fetchUrl = async (url) => { // 请求开始时重置状态,避免旧数据干扰 setLoading(false); setContent([]); try { const res = await fetch(url); const data = await res.json(); setContent(data.articles || []); setLoading(true); } catch (err) { console.error('请求失败:', err); setLoading(true); // 即使失败也停止加载动画 } }; useEffect(() => { // 仅当prop.link存在时发起请求 if (prop.link) { fetchUrl(prop.link); } // 清理函数:组件卸载时取消未完成的请求 const controller = new AbortController(); return () => controller.abort(); }, [prop.link]); // 依赖项:只有link变化时才重新执行 return ( <div className="cards"> {!loading && <img src={logo}/>} {prop.id === 1 && loading && content.map((element) => { if(element.description && element.urlToImage && element.title) return <Card image={element.urlToImage} description={element.description.slice(0,150)} title={element.title} key={element.url} />; }) } {prop.id === 2 && loading && content.map((element) => { return <Card image={element.url} description={`Eye color is ${element.eye_color}, Hair color is ${element.hair_color}, and is of age ${element.age}`} title={element.name} key={element.id} />; }) } {prop.num === 1 && <h1>yo</h1>} </div> ); } export default App;
关键说明:
useEffect的依赖项[prop.link]:确保仅当传入的link发生变化时才重新请求,彻底避免无意义的重复调用- 请求前重置状态:防止旧的
content在新请求完成前显示,提升用户体验 try/catch错误处理:捕获请求失败的情况,避免控制台报错,同时保证loading状态正常切换- AbortController:组件卸载时取消未完成的请求,防止内存泄漏和state更新警告
- 严格相等运算符
===:替换原代码中的==,避免隐式类型转换引发的潜在问题
内容的提问来源于stack exchange,提问作者Inferno
相关产品推荐
相关产品推荐

