今日已更新 412 条资讯 | 累计 19972 条内容
关于我们

Your fetch() Is Still Running After the User Left

Parsa Jiravand 2026年07月05日 17:12 1 次阅读 来源:Dev.to

When you fire a fetch() and the component that triggered it unmounts, the request keeps going. The server still processes it. When the response arrives, it calls back into whatever JavaScript it finds — a stale closure, a dead state setter, a global store that has already moved on. React's "Can't perform a state update on an unmounted component" warning is the polite version of this. The silent version is worse: results from an old query overwriting the current UI. These aren't mysterious race conditions. They're the predictable result of starting async work and never telling it to stop. The race condition hiding in every search box The search input is the clearest example. The user types "reac", your debounce fires a request. Before it lands, they finish typing "react" and you fire another. Two requests, in flight at the same time, and no guarantee about which one finishes first. If the "reac" request happens to be slower — network jitter, a cache miss, a heavier result set — it will land after "react" and overwrite the correct results with the wrong ones. The bug reproduces maybe one time in twenty on a local dev server, and consistently in production on a slow connection. The fix isn't smarter debouncing. It's cancelling the previous request when a new one starts. AbortController in plain terms AbortController is a browser-native API for cancelling async work. You create a controller, pass its signal to fetch() , and call controller.abort() to cancel. If the response hasn't arrived yet, the fetch promise rejects with an AbortError . const controller = new AbortController (); fetch ( ' /api/search?q=react ' , { signal : controller . signal }) . then ( res => res . json ()) . then ( data => setResults ( data )) . catch ( err => { if ( err . name === ' AbortError ' ) return ; // expected — not a real error setError ( err ); }); // Somewhere else, when we no longer need this request: controller . abort (); Two things to internalize: signal is how the controller knows

本文内容来源于互联网,版权归原作者所有
查看原文