跪拜 Guibai
← All articles
Frontend · Full-Stack · AI Programming

AsyncLocalStorage Fixes the Tab-Switching Race That Sends Wrong Module IDs to Your Backend

By 颜进强 ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Multitab admin UIs are full of serial chains that cross tab-switch boundaries; a naive location-based context always leaks the wrong page identity into permission checks. ALS-based context propagation gives you a framework-agnostic way to keep each chain's logical owner stable, and the documented pitfalls show exactly where the browser polyfill's patches conflict with a UI library like React 17.

Summary

A frontend admin app from the Juejin community had a classic serial-chain race: clicking a button in page A fires apiA, then while that await is pending, the user switches to tab B. apiA's callback then calls apiB, and if the request layer computes moduleId from the live location.pathname, apiB carries moduleId B instead of A. The fix is to stop reading location at request time and instead freeze the initiating page's moduleId into an AsyncLocalStorage context at the moment of the click.

The article walks through how the browser polyfill als-browser (1.0.1) patches Promise.then, setTimeout, and addEventListener to propagate context across await boundaries. A capture-phase document listener walks up the event target to find data-module-id, calls enterWith to seed the store, then restores to undefined using the native setTimeout after the event, so the seed doesn't leak to the next page. The axios interceptor then reads getPageModuleId() and injects it into FormData, JSON body, or query params.

Three pitfalls stand out: React 17's event delegation listener is registered with a frame of undefined, so it overwrites the seeded value unless you restore the native addEventListener from the polyfill's original symbol; the restore must use the un-patched setTimeout or the patch overwrites it; and you must restore to a stable undefined, not the pre-event prior, because 0ms restores from two interactions can reorder and write back an old seed. The build also needs transpile targets low enough (like ie 11) to compile async/await into Promise.then chains, otherwise the polyfill can't propagate.

Takeaways
— A serial chain like await apiA() then calling apiB() inside the callback will break if the user switches tabs between the two awaits, because the second request reads the current location, not the initiating page.
— The browser polyfill als-browser version 1.0.1 patches Promise.then, setTimeout, and addEventListener to propagate AsyncLocalStorage context across async boundaries.
— Seeding happens in the document capture phase (before React's event delegation) by walking up e.target to find a data-module-id attribute, then calling pageAls.enterWith({ moduleId }).
— Restoring context requires using the original native setTimeout (`setTimeout[Symbol.for('als-browser:original')]`), because the polyfilled version would overwrite the restore.
— React 17's event delegation listener is registered when the root container mounts, which binds a frame of undefined; clicking it pulls the frame back to undefined and erases the seed, so you must restore EventTarget.prototype.addEventListener from the original symbol in global.ts.
— Restore must set the store to undefined (stable baseline) rather than the pre-event value, because two rapid interactions can reorder 0ms timeouts and write an old seed back.
— The build must compile async/await into Promise.then chains (e.g., targets: { ie: 11 }) for the polyfill to propagate; native async runs won't be intercepted and will fall back to pathname lookup, risking mixed-up moduleIds.
— The same ALS mechanism supports traceId grouping, stale response dropping via opId, operation-level cancellation with AbortController, log context enrichment, and setState-after-unmount guards.
— ALS does not isolate React state across components or tabs; that still requires state keying or separate stores.
— Vue projects can apply this pattern without the React-specific pitfall because Vue lacks a single delegated event listener that would overwrite the seed.
Conclusions

The three pitfalls are the real value of this post: they map exactly where the browser ALS polyfill's global patches collide with framework event systems, and each fix is a targeted revert to a native API.

The approach effectively turns the DOM's event propagation into a context boundary, which is clever but also means every interaction that needs context must be able to find a data-module-id ancestor; any event path that skips the marked container will silently fall back to location.

Requiring a low transpile target (ie 11) just to make the polyfill work is a real cost; teams with modern builds that keep native async would need a different propagation strategy, like wrapping all async entry points explicitly.

Using a stable undefined restore instead of the previous value is a subtle but crucial correctness detail that prevents race conditions in the restore step itself, and it generalizes beyond this specific moduleId case.

Concepts & terms
AsyncLocalStorage (ALS)
A Node.js API (available natively via node:async_hooks) that stores context as a value associated with the current asynchronous execution chain. Any async callback spawned from within a run context inherits the same store value, and separate chains keep isolated copies. Browsers can achieve similar behavior via polyfills like als-browser.
als-browser
A browser polyfill (version 1.0.1 in this article) that patches Promise.then, setTimeout, and addEventListener to propagate AsyncLocalStorage context. It only works for code where async/await is transpiled into Promise.then chains; native async calls won't be intercepted.
enterWith()
An AsyncLocalStorage method that sets the context store for the current execution frame without running a new function callback. It takes effect for the rest of the current synchronous execution and any async operations spawned from it, until overwritten or restored.
From the discussion
Featured comments
去吧波波鸟

Wow, all three pitfalls were stepped on with real money and silver, indeed not searchable in tutorials. The React proxy part is especially harsh, the seed gets flushed out but no error is reported.

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗