react runtime_error ai_generated true

警告: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

其他格式: JSON · Markdown 中文 · English
92%修复率
88%置信度
1证据数
2023-06-20首次发现

版本兼容性

版本状态引入弃用备注
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.

generic

官方文档

https://reactjs.org/docs/hooks-effect.html

解决方案

  1. Define an async function inside useEffect and call it immediately, then return a cleanup function. Example: useEffect(() => { const fetchData = async () => { /* ... */ }; fetchData(); return () => { /* cleanup */ }; }, []);
  2. Use a custom hook like useAsyncEffect from a library (e.g., react-use) that handles async effects properly.
  3. For simple cases, use .then() and .catch() instead of async/await: useEffect(() => { fetch('/data').then(setData).catch(handleError); return () => { /* cleanup */ }; }, []);

无效尝试

常见但无效的做法:

  1. 90% 失败

    The async function still returns a Promise, which React interprets as an invalid cleanup return value.

  2. 85% 失败

    Promise.resolve() returns a Promise, still violating the rule that cleanup must be a function or undefined.

  3. 80% 失败

    The return value of the async function is a Promise, regardless of wrapping.