我想从组件上的事件处理程序触发异步操作,并在该操作完成后更新该组件中的某些 UI 状态。但是由于用户导航到另一个页面,该组件可能随时从 DOM 中删除。如果在操作尚未完成时发生这种情况,React 会记录以下警告:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
这是一个可重现的示例:
import { useState } from "react";
import ReactDOM from "react-dom";
// The router lib is a detail; just to simulate navigating away.
import { Link, Route, BrowserRouter } from "react-router-dom";
function ExampleButton() {
const [submitting, setSubmitting] = useState(false);
const handleClick = async () => {
setSubmitting(true);
await doStuff();
setSubmitting(false);
};
return (
<button onClick={handleClick} disabled={submitting}>
{submitting ? "Submitting" : "Submit"}
</button>
);
}
function doStuff() {
// Suppose this is a network request or some other async operation.
return new Promise((resolve) => setTimeout(resolve, 2000));
}
function App() {
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link> | <Link to="/other">Other</Link>
</nav>
<Route path="/" exact>
Click the button and go to "Other" page
<br />
<ExampleButton />
</Route>
<Route path="/other">Nothing interesting here</Route>
</BrowserRouter>
);
}
ReactDOM.render(<App />, document.querySelector("#root"));
您可以查看并运行示例 here .如果您在 2 秒后单击提交按钮,然后单击“其他”链接,您应该会在控制台上看到警告。是否有一种惯用的方式或模式来处理异步操作后需要状态更新的这些场景?
我试过的
我第一次尝试修复此警告是使用可变 ref 和
useEffect()
跟踪组件是否已卸载。钩:function ExampleButton() {
const [submitting, setSubmitting] = useState(false);
const isMounted = useRef(true);
useEffect(() => {
return () => {
isMounted.current = false;
};
}, []);
const handleClick = async () => {
setSubmitting(true);
await doStuff();
if (isMounted.current) setSubmitting(false);
};
return (
<button onClick={handleClick} disabled={submitting}>
{submitting ? "Submitting" : "Submit"}
</button>
);
}
注意对 setSubmitting()
的条件调用在 doStuff()
之后称呼。这个解决方案works ,但我对此不太满意,因为:
isMounted
跟踪似乎是一个低级细节,与该组件试图做什么无关,而不是我想在其他需要类似异步操作的地方重复。 useIsMounted()
钩子(Hook),似乎是 isMounted is an antipattern .是的,文章说的是Component.prototype.isMounted
方法,它不存在于我在这里使用的功能组件上,但我基本上是用 isMounted
模拟相同的功能引用。 更新:我也看到了拥有 a
didCancel
boolean variable 的模式在 useEffect 函数内部,并使用它在异步函数之后有条件地做一些事情(因为卸载或更新的依赖项)。我可以看到这种方法或使用可取消的 promise 如何在异步操作仅限于 useEffect()
的情况下工作得很好。并由组件挂载/更新触发。但是我看不到在事件处理程序上触发异步操作的情况下它们将如何工作。 useEffect 清理函数应该可以看到 didCancel
变量或可取消的 promise ,因此需要将它们提升到组件范围,使它们与 useRef
几乎相同上面提到的方法。所以我有点迷失在这里做什么。任何帮助将不胜感激! :D
最佳答案
确实 this.isMounted()
已弃用,并且使用 _isMounted 引用或实例变量是一种反模式,请注意在 this.isMounted()
时建议使用 _isMounted 实例属性作为临时迁移解决方案已弃用,因为最终它遇到了与 this.isMounted()
相同的问题这会导致内存泄漏。
该问题的解决方案是您的组件 - 无论是基于钩子(Hook)还是基于类的组件,都应该清理它的异步效果,并确保在卸载组件时,没有任何东西仍然持有对该组件的引用或需要在上下文中运行组件(基于钩子(Hook)的组件),这使得垃圾收集器能够在它启动时收集它。
在你的具体情况下,你可以做这样的事情
function ExampleButton() {
const [submitting, setSubmitting] = useState(false);
useEffect(() => {
if (submitting) {
// using an ad hoc cancelable promise, since ECMAScript still has no native way to cancel promises
// see example makeCancelable() definition on https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html
const cancelablePromise = makeCancelable(doStuff())
// using then since to use await you either have to create an inline function or use an async iife
cancelablePromise.promise.then(() => setSubmitting(false))
return () => cancelablePromise.cancel(); // we return the cleanup function
}
}, [submitting]);
const handleClick = () => {
setSubmitting(true);
};
return (
<button onClick={handleClick} disabled={submitting}>
{submitting ? "Submitting" : "Submit"}
</button>
);
}
现在请注意,无论卸载组件时发生什么情况,都没有更多可能/将要运行的与其相关的功能
关于javascript - 在异步回调上设置状态时防止 "React state update on unmounted component"警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68094318/