警告:useEffect 不能返回除函数以外的任何内容,函数用于清理。看起来你写了 useEffect(async () => ...) 或返回了一个 Promise。
Warning: useEffect must not return anything besides a function, which is used for clean-up. It looks like you wrote useEffect(async () => ...) or returned a Promise.
ID: react/useeffect-cleanup-return-promise
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React 16.8+ | active | — | — | — |
| React 17.x | active | — | — | — |
| React 18.x | active | — | — | — |
根因分析
useEffect 的清理函数必须是 undefined 或同步函数。返回 Promise(例如来自 async 函数)会导致此警告,因为 React 无法在清理上调用 .then()。
English
The cleanup function of useEffect must be either undefined or a synchronous function. Returning a Promise (e.g., from an async function) causes this warning because React cannot call .then() on the cleanup.
官方文档
https://reactjs.org/docs/hooks-effect.html解决方案
-
Define an async function inside useEffect and call it immediately, then return a cleanup function. Example: useEffect(() => { const fetchData = async () => { /* ... */ }; fetchData(); return () => { /* cleanup */ }; }, []); -
Use a custom hook like useAsyncEffect from a library (e.g., react-use) that handles async effects properly.
-
For simple cases, use .then() and .catch() instead of async/await: useEffect(() => { fetch('/data').then(setData).catch(handleError); return () => { /* cleanup */ }; }, []);
无效尝试
常见但无效的做法:
-
90% 失败
The async function still returns a Promise, which React interprets as an invalid cleanup return value.
-
85% 失败
Promise.resolve() returns a Promise, still violating the rule that cleanup must be a function or undefined.
-
80% 失败
The return value of the async function is a Promise, regardless of wrapping.