跪拜 Guibai
← Back to the summary

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

Switching Tabs Mixed Up All My API Calls — I Fixed It with AsyncLocalStorage

This article first explains exactly what problem AsyncLocalStorage (ALS for short) solves and its common use cases, then closes with a real-world implementation where requests carry a page moduleId. The backend Node.js environment has a native implementation (AsyncLocalStorage from node:async_hooks); browsers don't, so a polyfill is used: [email protected].

📌 Positioning: practical. Sections 1–4 are a quick principle overview (ALS veterans can jump straight to Section 5); the focus is Section 5 "Real-world Implementation + Three Pitfalls" — that's the part you won't find in tutorials.


1. What Problem Does ALS Actually Solve?

In one sentence: In the async world, context like "who is current / who does this belong to" gets lost, while ordinary variables either can't be read or get mixed up by concurrency. ALS lets this context "flow automatically along the async call chain", and each chain is isolated from the others.

Pain Point 1: Parameter Hell

A piece of cross-cutting information (like traceId, current user, tenant, language) has to be manually passed through a dozen function layers:

function component()      { return service(ctx); }
function service(ctx){ return util(ctx); }
function util(ctx)   { /* just wants to use ctx, but has to receive it and pass it down at every layer */ }

Every time you add a field or a layer, you have to change a bunch of function signatures. Context is an environment, not something to pass as a parameter.

Pain Point 2: Global Variables Get "Mixed Up" by Concurrency

If you store context in an ordinary global variable, multiple async operations will overwrite each other when they interleave:

let currentOp;   // global single value

async function operationA() {
  currentOp = 'A';
  const r = await request();     // during the wait, somewhere else might change currentOp to 'B'
  console.log(currentOp);     // expected 'A', might actually get 'B' ❌
}

async function operationB() {
  currentOp = 'B';
  await request();
}

During await, the "current operation" gets changed by another operation — that's the classic concurrency mixing in async.

ALS's Approach: A Context That "Follows the Call Chain, Each Going Its Own Way"

als.run({ op: 'A' }, async () => {
  await request();                     // anything happens during the wait
  console.log(als.getStore().op);   // always 'A' ✅
});

als.run({ op: 'B' }, async () => {
  await request();
  console.log(als.getStore().op);   // always 'B' ✅
});

2. Core Principle: Not a "Global Single Value", but "Each Async Chain Holds Its Own Copy"

This is the most essential difference between ALS and ordinary global variables. It relies on three actions working together:

Action Purpose API
Write "Tag" the current async chain als.run(data, fn) / als.enterWith(data)
Propagate On every await / .then / timer / callback, snapshot the tag and restore it before running the callback Done automatically by als-browser with low-level patches
Read Get the tag for "the current chain" als.getStore()

Key Mechanism: Callbacks "Put Their Own Tag on the Table Before Running, and Put It Back Afterward"

Before a callback runs → set the context to the one that was captured when this callback was registered
It runs (whatever it reads is this copy)
When the callback finishes → restore the context to what it was before the callback

Because JS runs only one piece of code at a time, two pieces never run simultaneously, so:

Think of it like a hat trick: before each piece of code goes on stage, its own tag is placed on the table; after it finishes, it's put back. Only one person is on stage at a time, so no one can misread another's tag.

Before callback A runs: place [A] → run A (reads A) → put it back
Before callback B runs: place [B] → run B (reads B) → put it back
     Only one runs at a time → never mixed

Prerequisite note (browser polyfill): als-browser propagates by patching Promise.then, setTimeout, addEventListener, etc. Therefore it only works for async/await that has been compiled into a Promise.then chain (this project's targets: ie11 satisfies that); native untranspiled async won't be intercepted.


3. Common Use Cases for ALS

ALS's value = turning "who does this step belong to / what environment is it in" into a context that flows automatically along the async chain and is isolated per chain. Here are typical scenarios in admin-style applications (sorted by cost-effectiveness):

# Scenario Problem Solved ALS Approach Cost-Effectiveness
1 Request context injection Fields every request must carry (page code, tenant, project, language…), don't want to pass them through layers The request interceptor uniformly calls getStore() and injects into body/query/header ⭐⭐⭐ Most stable
2 End-to-end trace / operation grouping One operation sends N requests, serial chains like A→B→C can't be grouped for debugging Generate traceId/operationId at the operation entry, inject along the chain, backend and logs can group ⭐⭐⭐
3 Stale response dropping (race conditions) Fast page switches / rapid searches, old requests returning later overwrite new state Each operation carries an incrementing opId, when a response arrives compare against the "current active opId", drop if mismatched ⭐⭐⭐
4 Operation-level batch cancellation After switching pages / closing modals, in-flight requests are still running and calling setState Context carries an AbortController, requests attach signal, one abort() cancels the whole group ⭐⭐⭐
5 Log / error context Logs and error reports don't know which page or operation they came from A unified logger reads ALS and automatically attaches { page, operation, user } ⭐⭐
6 setState-after-unmount guard When an async call returns after the component has left → warning / memory leak Context carries a "live token", callback first checks if (!alive) return ⭐⭐
7 General environment variables (multi-tenant/internationalization/feature flags) These values need to flow through all async logic Write to ALS at the entry, read with getStore() everywhere ⭐⭐
8 Slow operation analysis / event correlation "Clicked and froze for 3 seconds" without knowing which APIs were slow Aggregate the timing of all requests under one operationId ⭐

4. What ALS Is Not Good At (Avoid Misuse)

Requirement Suitable? Explanation
Request parameters/environment context that flows with async chain ✅ Strong ALS's intended use
UI state isolation across components / across tabs ❌ Not suitable That requires state keying / separate stores / component instance isolation; ALS only groups "which async result belongs to what", it doesn't isolate React state
Cancelling in-flight requests ⚠️ Half ALS only "carries" the controller/opId, actual cancellation still needs AbortController
Pure synchronous logic, no async boundaries ❌ No benefit Just passing parameters is clearer
Large objects residing in context ⚠️ Be careful Context lives as long as the async chain, only put small values like ids to avoid memory retention

5. Real-world Implementation: Requests Carry the Page ModuleId (Current Project State)

This is a concrete example of "using ALS for request context injection". Goal: make every HTTP request to the backend carry the current page's moduleId (permission code), and for serial async chains, after the user switches routes midway, the whole chain still stays bound to the moduleId of the page that initiated it. Business logic changes: zero (only the layout shell and global entry are touched, see 5.5).

5.1 The Problem

Every request to the backend relies on moduleId for permission checks. The difficulty is the time gap in serial dependency chains when the user switches pages:

// click on a button in page A
const r1 = await apiA();   // ① initiated while on A → carries A ✓
// ② A hasn't returned yet, user switches to page B
const r2 = await apiB();   // ③ if you take the real-time location, it would carry B ✗ mixed up

If the request layer computes moduleId using "real-time location.pathname", then as soon as step ② happens, all subsequent requests get the wrong page.

Before vs after (same scenario: "click button → switch tabs midway", look at the actual moduleId each request carries):

Timing Event Current page Before (real-time location) After (ALS chain stickiness)
t1 send apiA A A ✓ A ✓
— user switches to B B — —
t2 send apiB inside apiA's callback B B ✗ mixed A ✓ sticks to initiating page
t3 send apiC B B ✗ mixed A ✓

In one sentence: before the change, the latter half of a chain follows the "current page" (A→B→B); after the change, the whole chain is "locked at birth" to the initiating page (A→A→A). Another concurrently opened chain (initiated by a click on page B) sticks to B independently. No interference. 💡 At release you could paste a before/after DevTools Network screenshot here (looking at the moduleId parameter column) for stronger persuasion.

5.2 Overall Approach

Turn moduleId into a context that flows automatically along the async chain, rather than reading location at request time. Three actions:

Action What it does Location
① Mark Wrap each page/tab content container with data-module-id BasicLayout
② Write (seed) At the moment of click, find data-module-id upward from the clicked element, enterWith it into ALS; restore after the event ends pageScope.ts
③ Read (consume) Request interceptor calls getPageModuleId(): first read ALS, fallback to location if not found http/index.ts

Automatic propagation (await/.then inherit down the chain) is handled by als-browser, business code writes nothing.

5.3 Runtime Data Flow

 User clicks a button in page A
        │
        ▼
┌───────────────────────────────────────────────┐
│ ① document capture phase: find upward from e.target │  ← earlier than React's event delegation
│    hit "A" → pageAls.enterWith({moduleId:'A'})  │  ★write
│    native setTimeout(0) → restore after event ends │  ★restore (prevent leakage)
└───────────────────────────────────────────────┘
        │   the same event continues to bubble
        ▼
┌───────────────────────────────────────────────┐
│ ② React delegation → execute business handler: await apiA() │
│    (transpiled) apiA().then(cb)  ← .then frame at this moment = A │  ★propagate: snapshot A binds to cb
└───────────────────────────────────────────────┘
        │
        ▼
┌───────────────────────────────────────────────┐
│ ③ axios interceptor: getPageModuleId() → A → carry A ✓ │
└───────────────────────────────────────────────┘
        │
        ▼
 ④ apiA returns, callback executes under the "restored A frame" → even if location is now B
    → subsequent apiB().then(...) snapshots again → still A ✓ (the whole chain sticks to A)

5.4 Three "Non-obvious" Pitfalls (Hit and Fixed)

5.5 Key Implementation

Tech Stack Prerequisites

Item Version / Description
React / ReactDOM ^17.0.0 (event delegation is on the root container, so addEventListener needs restoring, see Pitfall ①)
Umi ^3.5.0 (src/global.ts loads before app.tsx)
antd ^4.14.0, @ant-design/pro-layout ^6.15.3 (Tabs / TabPane cached pages)
axios ^1.15.0 (request interceptor injects uniformly)
als-browser 1.0.1 (browser AsyncLocalStorage polyfill, must import before business/request code)
TypeScript / build ^4.2.2, targets: { ie: 11 } (ensures async/await is compiled into Promise.then chains so ALS can propagate)

① src/services/pageScope.ts — Seeding + Restore (Core)

const MODULE_KEY = 'moduleId';
const PAGE_MODULE_ID_ATTR = 'data-module-id';
const pageAls = new AsyncLocalStorage<{ moduleId?: string }>();

// Find the nearest page marker upward from the event target, get the interacted page's moduleId
const readModuleIdFromEvent = (e: Event): string | undefined => {
  try {
    let node: any = e.target;
    while (node && node.nodeType === 1) {
      if (node.getAttribute) {
        const attr = node.getAttribute(PAGE_MODULE_ID_ATTR);
        if (attr) return attr;
      }
      node = node.parentNode;
    }
  } catch (err) {
    // ignore exceptions, fallback
  }
  return undefined;
};

// Read: first read ALS scope, fallback to pathname if not found
export const getPageModuleId = (): string | undefined => {
  const store = pageAls.getStore();
  const storeId = store && store[MODULE_KEY];
  return storeId || resolveModuleIdByPath();
};

export function installPageScopeCapture(): void {
  if (typeof document === 'undefined') return;
  // Get the native setTimeout that hasn't been patched by als-browser, else the restore would be overwritten
  const rawSetTimeout =
    (setTimeout as any)[Symbol.for('als-browser:original')] || setTimeout;

  const handler = (e: Event) => {
    const moduleId = readModuleIdFromEvent(e);              // find data-module-id upward from e.target
    if (!moduleId) return;
    pageAls.enterWith({ [MODULE_KEY]: moduleId });          // seed
    rawSetTimeout(() => pageAls.enterWith(undefined), 0);   // restore to stable undefined
  };

  ['click', 'change', 'submit', 'keydown'].forEach((type) =>
    document.addEventListener(type, handler, true),         // capture phase, before React delegation
  );
}

② src/global.ts — Restore Native addEventListener (Pitfall ①)

import 'als-browser';

// als-browser binds listeners to the frame at registration; React 17's delegation listener has frame=undefined at mount,
// so clicking would pull the frame back to undefined and overwrite the seed → restore native implementation
const ORIGINAL = Symbol.for('als-browser:original');
(['addEventListener', 'removeEventListener'] as const).forEach((m) => {
  const cur = (EventTarget.prototype as any)[m];
  if (cur && cur[ORIGINAL]) (EventTarget.prototype as any)[m] = cur[ORIGINAL];
});

③ src/app.tsx — Startup Installation + Inject Menu Data

import { setPageMenuData, installPageScopeCapture } from '@/services/pageScope';

// module-level execution, before React mount
if (typeof window !== 'undefined') {
  installPageScopeCapture();
}
// in getInitialState: for path -> moduleId fallback resolution
setPageMenuData(menuData);

④ src/layouts/BasicLayout — Mark Each Cached Page Container

const tabModuleId = loopMenuItemDataByPathName(initialState?.menuData, tabItem.key)?.moduleId;
<TabPane key={tabItem.key}>
  <div data-module-id={tabModuleId} style={{ height: '100%' }}>
    {tabItem.component}
  </div>
</TabPane>

⑤ src/services/http/index.ts — Request Interceptor Reads and Injects

const pageModuleId = getPageModuleId();   // read ALS first, fallback to location

if (config.isFormData) {
  formData.append('moduleId', pageModuleId);                    // FormData
} else if (method === 'POST' || method === 'PUT') {
  config.data = { ...config.data, moduleId: pageModuleId };     // JSON body
} else {
  config.params = { ...config.params, moduleId: pageModuleId }; // GET query
}

6. FAQ

Q1: Does this approach only work with React? Can Vue use it? Yes. The ALS mechanism itself is framework-agnostic — essentially two steps: ① seed the interacted container's moduleId into ALS during the interaction capture phase; ② read ALS in the request interceptor and inject. Vue has native DOM events and axios interceptors too, just put data-module-id on the content container (e.g., the outer layer of <router-view>). It's even simpler: Pitfall ① (React 17 delegation wiping the seed) is React-specific, Vue doesn't have that delegation layer, so it won't hit that pitfall.

Q2: If the project has "untranspiled native async/await", will it break? It will degrade. als-browser propagates by patching Promise.then, only works for async/await compiled into Promise.then chains. If a piece of code runs as native async (target too high, not using Babel), .then isn't intercepted → chain breaks → getStore() reads no seed → falls back to pathname-based fallback (might mix up). Solution: lower the build target / browserslist so async is compiled into regenerator or .then chains (this project's targets: { ie: 11 } suffices).

Q3: What's the essential difference from "using a global variable / sessionStorage / Redux to store the current moduleId"? The difference is "one copy vs each gets its own copy":

Approach After switching tabs, what moduleId does the in-flight old chain read? Result
Global variable / Redux / sessionStorage store "current page moduleId" Gets overwritten to the new page's value (only one global, switching overwrites) Mixed up
Read real-time location at request time Same as above, follows current page Mixed up
ALS Each chain freezes its own copy at initiation No mixing, sticks to initiating page

In one sentence: global variable is "one table with one card, everyone fights to cover it"; ALS is "each piece of code holds its own card in hand".


7. One-Sentence Summary

ALS turns "who does this step belong to / what environment is it in" into a context that automatically flows along async call chains, isolated per chain. It solves the fundamental problem of "context getting lost or mixed up in async"; moduleId injection, trace grouping, stale response dropping, operation-level cancellation, log context, unmount guards — all are different consumers of the same mechanism.

Comments

Top 2 from juejin.cn, machine-translated. The original thread is authoritative.

颜进强

The pain points I encountered in recent requirement development, I summarized them, hoping they can help you.

去吧波波鸟

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.