常见报错速查
React 报错信息量通常很大,但初次见到会懵。最高频的几类:Hooks 规则错误(违反调用顺序/条件调用)、key 警告(数组渲染缺 key)、props 类型错误、卸载后 setState、跨域与 404。
排查工具链:React DevTools(组件树 + Profiler)、浏览器控制台(绝大多数警告会指明文件与行号)、source map(Vite 开发模式报错可直接定位)。TS 项目再加上类型检查,绝大多数低级错误在编辑器里就拦住了。
- Hooks 规则错误:99% 是在 if/循环/嵌套函数里调用了 Hook
- “Each child in a list should have a unique key”:map 少了 key
- 先看控制台黄字警告——React 的错误提示质量是框架里最好的
排错
// 常见报错对照与修复 // ① Hooks 规则错误: // Error: Invalid hook call / React Hook "useState" is called conditionally function Bad({ ok }) { if (ok) { const [v, setV] = useState(0); // ✗ 不能放在条件里 } } function Good({ ok }) { const [v, setV] = useState(0); // ✓ 永远在顶层调用 if (!ok) return null; return <p>{v}</p>; } // ② key 警告:Warning: Each child in a list should have a unique "key" {list.map(item => <li>{item}</li>)} // ✗ {list.map(item => <li key={item.id}>{item}</li>)} // ✓ // ③ 卸载后 setState(React 18 不再警告,但仍要清理) useEffect(() => { const timer = setTimeout(() => setX(1), 3000); return () => clearTimeout(timer); // ✓ 清理就不会打到已卸载组件 }, []); // ④ props 类型错误:Warning: Failed prop type / 默认无检查 // 根本解法:TypeScript + interface PropsUser { name: string; age: number } // ⑤ Cannot read property 'x' of undefined:fetch 数据未到手就渲染 // 修复:loading 兜底(if (!data) return <Loading/>)
本节要点排错顺序:看控制台警告 → 定位报错文件 → 查 Hooks 顺序 / key / props 类型 / 异步兜底。




