Skip to content

linter: react/immutability flags a let declared inside a callback and reassigned by a closure within it (regression in 8612f43) #28401

Closed
ngrok/mantle
#1666

Description

@shiroyasha9

What version of Oxlint are you using?

What command did you run?

oxlint -c .oxlintrc.json -f unix repro.ts

What does your .oxlintrc.json (or oxlint.config.ts) config file look like?

{
  "categories": { "correctness": "off" },
  "plugins": ["react"],
  "rules": { "react/immutability": "error" }
}

What happened?

react/immutability reports a let that is declared inside a callback when a closure inside that callback reassigns it. The variable is created each time the callback runs, so it can't carry a stale value across renders.

Repro

import { useEffect, useState } from "react";

// False positive: `last` is declared inside the effect, so it never crosses a render.
export function useTicker(isPlaying: boolean) {
	const [total, setTotal] = useState(0);
	useEffect(() => {
		if (!isPlaying) return;
		let last = Date.now();
		const id = setInterval(() => {
			const now = Date.now();
			setTotal((t) => t + (now - last));
			last = now;
		}, 1000);
		return () => clearInterval(id);
	}, [isPlaying]);
	return total;
}

// False positive, async variant.
export function useAfterRun(run: () => Promise<void>) {
	useEffect(() => {
		let timeoutId: ReturnType<typeof setTimeout> | undefined;
		const go = async () => {
			await run();
			timeoutId = setTimeout(() => {}, 10);
		};
		go();
		return () => clearTimeout(timeoutId);
	}, [run]);
}

// Control, correctly reported: `count` is a render-scope local.
export function useCounter() {
	let count = 0;
	useEffect(() => {
		count = 1;
	});
	return count;
}

Output

On main:

repro.ts:12:4: Cannot reassign variable after render completes [Error/react(immutability)]
repro.ts:25:4: Cannot reassign variable in async function [Error/react(immutability)]
repro.ts:36:3: Cannot reassign variable after render completes [Error/react(immutability)]
repro.ts:36:3: Cannot modify local variables after render completes [Error/react(immutability)]

Expected: only the two errors on the control, useCounter.

Build useTicker useAfterRun useCounter (control)
oxlint main 6586050 false positive at 12:4 false positive at 25:4 2 errors at 36:3
oxlint 1.90.0 none none 2 errors at 36:3
eslint-plugin-react-hooks 7.1.1 none none 2 errors at 35:12, 36:3
eslint-plugin-react-hooks 7.1.1-canary-dc9aed36-20261027 none none 2 errors at 35:12, 36:3

The canary is built from React main after react/react#37513, the commit #26893 ports.

Cause

  • In get_context_reassignment, child_context_variables picks up the params, context declarations and stores of every function it visits, nested function expressions included.
  • So last becomes a tracked variable for the closures inside the effect.
  • Upstream adds to contextVariables only when !isFunctionExpression, with the comment "We only track reassignments of variables defined in the outer component or hook" (ValidateLocalsNotReassignedAfterRender.ts#L134-L176).

Suggested fix

Track only the bindings of the outer component or hook, as upstream does:

     let mut child_context_variables = context_variables.clone();
-    for param in &func.params {
-        let place = match param {
-            ParamPattern::Place(place) => place,
-            ParamPattern::Spread(spread) => &spread.place,
-        };
-        child_context_variables.insert(place.identifier);
+    if !is_function_expression {
+        for param in &func.params {
+            let place = match param {
+                ParamPattern::Place(place) => place,
+                ParamPattern::Spread(spread) => &spread.place,
+            };
+            child_context_variables.insert(place.identifier);
+        }
+        collect_outer_context_variables(func, &mut child_context_variables);
     }
-    collect_outer_context_variables(func, &mut child_context_variables);
  • With this patch, the repro reports only useCounter.

  • cargo test -p oxc_react_compiler --no-fail-fast passes except one snapshot, error.invalid-nested-closure-captures-intermediate-parameter, which 8612f43 added:

    function Component() {
      return ((count) => () => count++)(0);
    }
    • The canary doesn't report this fixture either, even with a useState(0) call added so the plugin compiles it. Oxlint main reports that version at 5:28.
    • To keep that error, the guard would need to tell a function that runs during render (this IIFE) apart from a callback that runs later (an effect).
  • Happy to open a PR either way.

Impact

  • In our React Native app (2,789 files), this adds 12 react/immutability errors on main:
    • 7 "Cannot reassign variable after render completes" and 5 "Cannot reassign variable in async function".
    • Where the let is declared: 7 in useEffect, 3 in useCallback, 1 in an event handler, 1 in a lazy useState initializer.
  • The patch removes all 12.
  • eslint-plugin-react-hooks 7.1.1 and the canary report none of them.

Issue improved with AI assistance. I verified every claim above by running the oxlint builds and both ESLint plugin versions, bisecting, and reading the referenced source.

Activity

  1. added
    A-linter
    on Oct 29, 2026
  2. added theissue type on Oct 29, 2026
  3. shiroyasha9 commented on Oct 29, 2026

    @shiroyasha9
    Author

    Opened #28402 with the fix. It goes back to tracking only the component or hook bindings, as upstream does, and adds fixtures for the sync and async cases.

  4. dnalborczyk commented on Nov 3, 2026

    @dnalborczyk

    Confirming this shipped in the 1.91.0 release (1.90.0 is clean on the same code). In a real-world Next.js monorepo it produced 42 new react/immutability errors, all effect-local or handler-local lets reassigned from a nested callback — e.g. the react.dev cancellation pattern:

    useEffect(() => {
      let cancelled = false
      let cleanup: (() => void) | undefined
      void load().then((attach) => {
        if (cancelled) return
        cleanup = attach() // Cannot reassign variable after render completes
      })
      return () => {
        cancelled = true
        cleanup?.()
      }
    }, [])

    We've pinned to 1.90.0 for now.

  5. added a commit that references this issue on Nov 4, 2026
    3d3a6f4
  6. 16 remaining items

  7. iki commented on Nov 20, 2026

    @iki

    I reran the original TypeScript reproduction on Windows x64 with the published Oxlint 1.94.0, matching plugins, and the unsuppressed react/immutability rule under --type-aware.

    The callback-local writes on lines 12 and 25 were clean on 1.94.0. The intentionally invalid render-scope write on line 36 still produced both expected diagnostics. Running the same fixture in separate frozen installs gave the same result on 1.90.0 and reproduced both extra diagnostics on 1.91.0. Thanks for fixing this in #28820.

    I also ran the original reproduction with Oxlint and plugins 1.90.0 against oxlint-tsgolint@7.0.2007, the type checker used for the 1.94.0 run. With --type-aware, lines 12 and 25 stayed clean and line 36 produced the two expected diagnostics.

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

Metadata

Metadata

Assignees

Labels

A-linter

Type

Fields

Priority

None yet

Effort

None yet

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions