Minified React error #329; 访问 https://reactjs.org/docs/error-decoder.html?invariant=329 获取完整消息,或使用非压缩的开发环境查看完整错误。
Minified React error #329; visit https://reactjs.org/docs/error-decoder.html?invariant=329 for the full message or use the non-minified dev environment for full errors.
ID: react/error-minified-react-error-329
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React 18.2.0 | active | — | — | — |
| React 17.0.2 | active | — | — | — |
| React 16.14.0 | active | — | — | — |
根因分析
React 内部不变性违反 #329 表示状态更新被调用在一个已卸载的组件上,通常是由于异步操作(例如 setTimeout、fetch)在组件卸载后完成。
English
React's internal invariant violation #329 indicates a state update was called on a component that is not mounted, typically due to an asynchronous operation (e.g., setTimeout, fetch) completing after the component unmounts.
官方文档
https://reactjs.org/docs/error-decoder.html?invariant=329解决方案
-
Use a cleanup function in useEffect to cancel asynchronous operations. Example: useEffect(() => { const controller = new AbortController(); fetch(url, { signal: controller.signal }); return () => controller.abort(); }, []); -
Check if the component is mounted using a ref before calling setState. Example: const isMounted = useRef(true); useEffect(() => { return () => { isMounted.current = false; }; }, []); then check if (isMounted.current) before setState. -
Use a state management library like Zustand or Redux that handles updates outside the component lifecycle, avoiding direct setState calls.
无效尝试
常见但无效的做法:
-
Use componentWillUnmount lifecycle method in a function component
100% 失败
Function components do not have componentWillUnmount; you must use useEffect cleanup instead.
-
Add a try-catch around the state update call
95% 失败
The error is not a thrown exception; it's an invariant violation that bypasses try-catch.
-
Call setState with a callback to ensure it's executed after the update
90% 失败
setState callbacks don't prevent updates on unmounted components.