Skip to content

Bug: Suspense fallback stays forever when an async action settles before the fallback commits #38431

Backlog

Description

@CinchBlue

React version: 19.3.1 and 19.3.0-canary-edae846a-20261125, development and production. Chrome and Firefox.

Steps to reproduce

Save the page below as async-action-fallback.html and open it. ?v=<version> and &dev pick the build.

  1. Mount a <Suspense> boundary inside a hidden <Activity>.
  2. Start an async action that updates state inside the boundary.
  3. The hidden render suspends on the action and renders the fallback. Make it yield there and finish the action in
    that gap, before the fallback commits.
  4. Show the <Activity>.

Current behaviour

The fallback stays. Nothing is pending and nothing is logged. If the action finishes after the fallback commits, the
content appears.

Expected behaviour

The boundary retries and shows the new state.

Cause

The thenables made in ReactFiberAsyncAction.js (entangleAsyncAction and chainThenableValue) only push to a
listener array in then. The retry listener is attached at commit. If the thenable has settled by then, the array has
already been drained and the listener is never called. useTransition state goes through the second one.

Proposed fix

async-action-fallback.patch: a listener added after settling is scheduled (a microtask, or an immediate Scheduler task
where the host has no microtasks). Includes two tests that fail without the change.

Repro page: async-action-fallback.html
<!doctype html>
<meta charset="utf-8">
<title>React: Suspense fallback stays forever when an async action settles before the fallback commits</title>
<pre id="log">running...</pre>
<div id="root"></div>
<script type="module">
// ?v=<react version, default 19.3.1>  &dev for the development build
const q = new URLSearchParams(location.search), v = q.get("v") || "19.3.1", dev = q.has("dev") ? "?dev" : "";
const React = (await import(`https://esm.sh/react@${v}${dev}`)).default;
const { createRoot } = (await import(`https://esm.sh/react-dom@${v}/client${dev}`)).default;
const { createElement: h, Activity, Suspense, useState, startTransition } = React;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

// settle: "during" the fallback render, or "after" the fallback has committed (control)
async function run(settle) {
  const set = {};
  let finish, onFallback = null;
  const action = new Promise((r) => (finish = r));
  function Counter() {
    const [count, setCount] = useState(0);
    set.count = setCount;
    return h("p", null, `count ${count}`);
  }
  // Once armed, the fallback queues `finish` and blocks long enough for React to yield before committing.
  function Fallback() {
    if (onFallback) {
      const then = onFallback;
      onFallback = null;
      const channel = new MessageChannel();
      channel.port1.onmessage = then;
      channel.port2.postMessage(null);
      for (const end = performance.now() + 30; performance.now() < end; );
    }
    return h("p", null, "loading");
  }
  const content = h(Suspense, { fallback: h(Fallback) }, h(Counter));
  function App() {
    const [mode, setMode] = useState("hidden");
    set.mode = setMode;
    return h(Activity, { mode }, content);
  }
  const root = createRoot(document.getElementById("root"));
  root.render(h(App));
  await sleep(500);                                       // 1. hidden content is prerendered
  if (settle === "during") onFallback = () => finish();
  startTransition(async () => { set.count(1); await action; }); // 2. async action, pending
  await sleep(700);                                       // 3. hidden content suspends on the action
  if (settle === "after") finish();
  await sleep(300);
  const button = document.body.appendChild(document.createElement("button"));
  button.onclick = () => set.mode("visible");             // 4. show it
  button.click(); button.remove();
  await sleep(1500);
  const text = document.getElementById("root").innerText.trim();
  root.unmount();
  return text;
}

const during = await run("during"), after = await run("after");
const line = (name, text) => `${name}: DOM shows "${text}", expected "count 1" -> ${text === "count 1" ? "ok" : "BUG"}`;
document.getElementById("log").textContent =
  [`react ${React.version}${dev ? " development" : " production"}`,
   line("action settles while the fallback renders", during), line("action settles after the fallback commits (control)", after)].join("\n");
document.title = "done";
</script>
Proposed fix with tests: async-action-fallback.patch (against main edae846a9a)
diff --git a/packages/react-reconciler/src/ReactFiberAsyncAction.js b/packages/react-reconciler/src/ReactFiberAsyncAction.js
index 0de3f31..3f98e48 100644
--- a/packages/react-reconciler/src/ReactFiberAsyncAction.js
+++ b/packages/react-reconciler/src/ReactFiberAsyncAction.js
@@ -31,6 +31,11 @@ import {
 } from 'shared/ReactFeatureFlags';
 import {clearEntangledAsyncTransitionTypes} from './ReactFiberTransitionTypes';
 
+import {supportsMicrotasks, scheduleMicrotask} from './ReactFiberConfig';
+import {
+  scheduleCallback as Scheduler_scheduleCallback,
+  ImmediatePriority as ImmediateSchedulerPriority,
+} from './Scheduler';
 import noop from 'shared/noop';
 import reportGlobalError from 'shared/reportGlobalError';
 
@@ -84,7 +89,14 @@ export function entangleAsyncAction<S>(
       status: 'pending',
       value: undefined,
       then(resolve: void => mixed) {
-        entangledListeners.push(resolve);
+        if (entangledThenable.status === 'pending') {
+          entangledListeners.push(resolve);
+        } else {
+          // The listeners have already been notified. A retry can be attached
+          // this late if the actions finish between the render that suspended
+          // and its commit, so it must still be called.
+          scheduleLateListener(resolve);
+        }
       },
     };
     currentEntangledActionThenable = entangledThenable;
@@ -100,6 +112,16 @@ export function entangleAsyncAction<S>(
   return thenable;
 }
 
+function scheduleLateListener(listener: () => mixed) {
+  if (supportsMicrotasks) {
+    scheduleMicrotask(listener);
+  } else {
+    Scheduler_scheduleCallback(ImmediateSchedulerPriority, () => {
+      listener();
+    });
+  }
+}
+
 function pingEngtangledActionScope() {
   if (--currentEntangledPendingCount === 0) {
     if (enableProfilerTimer && enableComponentPerformanceTrack) {
@@ -154,7 +176,18 @@ export function chainThenableValue<T>(
     value: null,
     reason: null,
     then(resolve: T => mixed) {
-      listeners.push(resolve);
+      if (thenableWithOverride.status === 'pending') {
+        listeners.push(resolve);
+      } else {
+        // Same as above: a listener added after settling must still be called.
+        scheduleLateListener(() =>
+          resolve(
+            thenableWithOverride.status === 'fulfilled'
+              ? result
+              : (undefined as any),
+          ),
+        );
+      }
     },
   };
   thenable.then(
diff --git a/packages/react-reconciler/src/__tests__/ReactAsyncActionLateListener-test.js b/packages/react-reconciler/src/__tests__/ReactAsyncActionLateListener-test.js
new file mode 100644
index 0000000..ca0615e
--- /dev/null
+++ b/packages/react-reconciler/src/__tests__/ReactAsyncActionLateListener-test.js
@@ -0,0 +1,139 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @emails react-core
+ * @jest-environment node
+ */
+
+'use strict';
+
+let React;
+let ReactNoop;
+let Scheduler;
+let act;
+let waitFor;
+let Activity;
+let Suspense;
+let useState;
+let startTransition;
+
+describe('async action that settles before the fallback commits', () => {
+  beforeEach(() => {
+    jest.resetModules();
+
+    React = require('react');
+    ReactNoop = require('react-noop-renderer');
+    Scheduler = require('scheduler');
+    const InternalTestUtils = require('internal-test-utils');
+    act = InternalTestUtils.act;
+    waitFor = InternalTestUtils.waitFor;
+    Activity = React.Activity;
+    Suspense = React.Suspense;
+    useState = React.useState;
+    startTransition = React.startTransition;
+  });
+
+  it('retries the boundary', async () => {
+    let setCount;
+    let setMode;
+    function Counter() {
+      const [count, _setCount] = useState(0);
+      setCount = _setCount;
+      Scheduler.log('Counter ' + count);
+      return <span prop={count} />;
+    }
+    function Fallback() {
+      Scheduler.log('Fallback');
+      return <span prop="loading" />;
+    }
+    const content = (
+      <Suspense fallback={<Fallback />}>
+        <Counter />
+      </Suspense>
+    );
+    function App() {
+      const [mode, _setMode] = useState('hidden');
+      setMode = _setMode;
+      return <Activity mode={mode}>{content}</Activity>;
+    }
+
+    const root = ReactNoop.createRoot();
+    await act(() => root.render(<App />));
+    Scheduler.unstable_clearLog();
+
+    // Start an async action and keep it pending
+    let finishAction;
+    startTransition(async () => {
+      setCount(1);
+      await new Promise(resolve => (finishAction = resolve));
+    });
+
+    // The hidden content suspends on the action. Yield after the fallback has
+    // rendered but before it commits, and let the action finish in that gap.
+    await waitFor(['Fallback']);
+    finishAction();
+    for (let i = 0; i < 10; i++) {
+      await null;
+    }
+    await act(() => {});
+    Scheduler.unstable_clearLog();
+
+    await act(() => setMode('visible'));
+    Scheduler.unstable_clearLog();
+
+    expect(root).toMatchRenderedOutput(<span prop={1} />);
+  });
+
+  it('retries a boundary that suspended on useTransition state', async () => {
+    let setMode;
+    let start;
+    function Counter() {
+      const [count] = useState(0);
+      start = React.useTransition()[1];
+      Scheduler.log('Counter ' + count);
+      return <span prop={count} />;
+    }
+    function Fallback() {
+      Scheduler.log('Fallback');
+      return <span prop="loading" />;
+    }
+    const content = (
+      <Suspense fallback={<Fallback />}>
+        <Counter />
+      </Suspense>
+    );
+    function App() {
+      const [mode, _setMode] = useState('hidden');
+      setMode = _setMode;
+      return <Activity mode={mode}>{content}</Activity>;
+    }
+
+    const root = ReactNoop.createRoot();
+    await act(() => root.render(<App />));
+    Scheduler.unstable_clearLog();
+
+    // Start an async action and keep it pending
+    let finishAction;
+    start(async () => {
+      await new Promise(resolve => (finishAction = resolve));
+    });
+
+    // The hidden content suspends on the action. Yield after the fallback has
+    // rendered but before it commits, and let the action finish in that gap.
+    await waitFor(['Counter 0', 'Fallback']);
+    finishAction();
+    for (let i = 0; i < 10; i++) {
+      await null;
+    }
+    await act(() => {});
+    Scheduler.unstable_clearLog();
+
+    await act(() => setMode('visible'));
+    Scheduler.unstable_clearLog();
+
+    expect(root).toMatchRenderedOutput(<span prop={0} />);
+  });
+});

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions