Skip to content

[compiler] Fix refs false positive for IntersectionObserver callbacks - #37764

Merged
javache merged 3 commits into
react:mainfrom
akasakariko:fix/intersection-observer-refs
Oct 14, 2026
Merged

javache merged 3 commits into
react:mainfrom
akasakariko:fix/intersection-observer-refs

Conversation

@akasakariko

@akasakariko akasakariko commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #35982

This pull request resolves a false positive ref access error during render when passing callbacks to the global IntersectionObserver constructor

Cumulative implementation:

  • Both TypeScript and Rust compiler backends model the global IntersectionObserver constructor with a deferred frozen callback (Effect.Freeze), read-only options (Effect.Read), and a mutable non-aliasing return value
  • NewExpression instructions reuse standard call-effect ref validation rather than branching to a separate path, ensuring unknown constructors receiving refs directly or via callbacks are rejected during render

Review follow-up updates:

  • Switched generic return type from BuiltInObject shape to Poly (Type::Poly in Rust and {kind: 'Poly'} in TypeScript)
  • Updated Rust constructor section heading comment in compiler/crates/react_compiler_hir/src/globals.rs
  • Simplified positive compiler fixture allow-ref-access-in-intersection-observer.ts to two minimal hooks covering construction with and without options
  • Retained original useCallback, useMemo, and options reproduction as an ESLint integration test in packages/eslint-plugin-react-hooks/__tests__/ReactCompilerRuleTypescript-test.ts
  • Added compiler negative fixture error.invalid-ref-in-unknown-constructor.js for passing a direct ref argument to an unknown constructor
  • Added compiler negative fixture error.invalid-mutate-hook-value-in-intersection-observer.js for mutating a useMemo-returned array inside an observer callback
  • Added ESLint test cases for no-options positive observer usage and direct-ref negative constructor usage while keeping shadowed constructor negative coverage

How this was tested

Local verification completed across compiler and root suites:

  • TypeScript compiler fixture suite passed (1831/1831)
  • Rust compiler fixture suite passed (1831/1831)
  • TypeScript and Rust parity suite passed (1830/1830)
  • Compiler Jest test suite passed with 44 tests and 40 snapshots in 16 suites
  • ESLint test suite passed with 5086 tests in 4 suites, including focused 15 TypeScript tests
  • Cargo workspace checks passed: cargo check --workspace --all-targets and cargo test --workspace (49 tests)
  • Babel AST tests passed with 1810 roundtrips, 1811 scope roundtrips, and 1796 scope renames (12 rename cases skipped by harness)
  • Formatting and static typing checks passed: compiler lint, compiler tsc, ESLint tsc, yarn linc, Prettier check on changed files, and rustfmt on changed Rust files
  • Full test suites ran before final comment-only Rust heading change, and final rustfmt passed
  • Fixture tests compile and compare diagnostics and output without claiming browser execution

Qualification

  • Strict command cargo clippy -p react_compiler_hir -p react_compiler_validation --all-targets -- -D warnings fails on pre-existing implicit_saturating_sub and incompatible_msrv diagnostics in compiler/crates/react_compiler_diagnostics/src/code_frame.rs
  • Diagnostic reproduced independently at original baseline commit a32292d under the same toolchain
  • Standard Clippy emits 86 warnings, exactly matching baseline with zero new warnings introduced

@meta-cla meta-cla Bot added the CLA Signed label Oct 6, 2026
@github-actions

github-actions Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

Comparing: 278794d...3af4393

Critical size changes

Includes critical production bundles, as well as any change greater than 2%:

Name +/- Base Current +/- gzip Base gzip Current gzip
oss-stable/react-dom/cjs/react-dom.production.js = 7.35 kB 7.35 kB -0.10% 1.96 kB 1.96 kB
oss-stable/react-dom/cjs/react-dom-client.production.js = 626.06 kB 626.06 kB = 110.63 kB 110.63 kB
oss-experimental/react-dom/cjs/react-dom.production.js = 7.36 kB 7.36 kB -0.05% 1.96 kB 1.96 kB
oss-experimental/react-dom/cjs/react-dom-client.production.js = 697.27 kB 697.27 kB = 122.07 kB 122.07 kB
facebook-www/ReactDOM-prod.classic.js = 716.04 kB 716.04 kB = 125.29 kB 125.29 kB
facebook-www/ReactDOM-prod.modern.js = 706.36 kB 706.36 kB = 123.73 kB 123.73 kB

Significant size changes

Includes any change greater than 0.2%:

(No significant changes)

Generated by sizebot against 3af4393

@eps1lon eps1lon changed the title Fix ref access false positive in IntersectionObserver callbacks [compiler] Fix ref access false positive in IntersectionObserver callbacks Oct 6, 2026
@javache

javache commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Changes look reasonable, but can you reduce the fixtures in a smaller set which repro the core issue?

@akasakariko

Copy link
Copy Markdown
Contributor Author

@javache Reduced the seven compiler fixtures to one positive reproduction and one negative shadowed-constructor case in bcbc5f1, while retaining the two ESLint integration tests

Also reproduced the Rust CI failure and aligned the Rust globals and ref validation with TypeScript

Local validation passes: 1829 fixtures for each backend, 1828 Rust/TypeScript parity cases, 44 compiler unit tests, 49 Rust tests, and 5084 ESLint tests

Strict Clippy still hits the same pre-existing MSRV errors on the original commit, with zero new warnings in the full baseline comparison

The new GitHub CI runs still need to execute

@javache

javache commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Looks good, the CI failures seem unrelated.

Two things I'd like resolved before this lands, both about behaviour outside IntersectionObserver:

  1. new Thing(ref) on an unmodeled constructor now errors. Routing NewExpression through the effects path means a bare ref reaches validateNoRefPassedToFunction, which flags kind: 'Ref'. The old default: arm used validateNoRefValueAccess, which doesn't.
    That's probably the right call, since it makes new X(ref) consistent with x(ref). Please add a fixture back for this and mention it in the description.
  2. Effect.Freeze is transitive over the callback's captures. freezeValue recurses into the lowered func's context and enableTransitivelyFreezeFunctionExpressions defaults to true, so a callback that mutates a useMemo result should now be a frozen-mutation error where it previously compiled. Seems reasonable, but worth a fixture pinning it.

Smaller, non-blocking:

  • returnType: BuiltInObjectId claims a shape the observer doesn't have (observe/disconnect miss it). Map/Set each get a dedicated shape, either add one or use Poly.
  • Add new IntersectionObserver(cb) with options omitted; it's the most common form and currently untested.
  • The Rust entry sits under the // Map, Set, WeakMap, WeakSet constructors comment — worth updating that heading.

@akasakariko akasakariko changed the title [compiler] Fix ref access false positive in IntersectionObserver callbacks [compiler] Fix refs false positive for IntersectionObserver callbacks Oct 13, 2026
@akasakariko

Copy link
Copy Markdown
Contributor Author

Addressed the follow-up in 3af4393

  • Added negative coverage for passing a ref directly to an unknown constructor and for mutating a useMemo result inside the observer callback
  • Covered construction without options and reduced the positive compiler fixture to two minimal hooks, retaining the original reproduction in the ESLint tests
  • Switched the constructor return type to Poly in both TypeScript and Rust and updated the Rust constructor section comment

Local validation passes for all 1831 fixtures in each backend, 1830 TS/Rust parity fixtures, 5086 ESLint tests, compiler Jest, Cargo checks/tests, Babel AST checks, formatting, lint, and typechecks

Strict Clippy still reports existing diagnostics in react_compiler_diagnostics/src/code_frame.rs, independently reproduced at the original baseline, with no new warnings

The six workflows for the new revision require maintainer approval before they can run

@javache
javache merged commit efa3189 into react:main Oct 14, 2026
481 of 482 checks passed
akasakariko added a commit to akasakariko/akasakariko that referenced this pull request Oct 14, 2026
sokra pushed a commit to vercel/next.js that referenced this pull request Oct 15, 2026
[diff
react/react@07dde64d...99c106c4](react/react@07dde64...99c106c)

<details>
<summary>React upstream changes</summary>

- react/react#37852
- react/react#37850
- react/react#37846
- react/react#37764

</details>

---------

Co-authored-by: next-js-bot[bot] <279046576+next-js-bot[bot]@users.noreply.github.com>
Co-authored-by: Josh Story <[email protected]>
zhoubiao188 added a commit to zhoubiao188/react that referenced this pull request Oct 22, 2026
…backs

Both constructors only retain the callback and invoke it after render, so
reading a ref inside the callback is safe. Without a modeled signature they
fall back to the default effects for unknown constructors, which report

    Cannot access refs during render

for the common `new ResizeObserver(() => ref.current)` pattern. That is the
same false positive that react#37764 fixed for `IntersectionObserver`.

Model both observers in the TypeScript and Rust compilers. Each takes a
single constructor argument — unlike `IntersectionObserver`, whose options
object is a second constructor parameter, `ResizeObserver` and
`MutationObserver` receive their options in `observe(target, options)` — so
both are modeled with a single `Freeze`d callback.

The fixtures cover the accepted patterns (including `observe` options) plus
one negative case asserting that mutating a hook value inside the callback
is still rejected.
zhoubiao188 added a commit to zhoubiao188/react that referenced this pull request Oct 22, 2026
…backs

Both constructors only retain the callback and invoke it after render, so
reading a ref inside the callback is safe. Without a modeled signature they
fall back to the default effects for unknown constructors, which report

    Cannot access refs during render

for the common `new ResizeObserver(() => ref.current)` pattern. That is the
same false positive that react#37764 fixed for `IntersectionObserver`.

Model both observers in the TypeScript and Rust compilers. Each takes a
single constructor argument — unlike `IntersectionObserver`, whose options
object is a second constructor parameter, `ResizeObserver` and
`MutationObserver` receive their options in `observe(target, options)` — so
both are modeled with a single `Freeze`d callback.

The fixtures cover the accepted patterns (including `observe` options) plus
one negative case asserting that mutating a hook value inside the callback
is still rejected.
javache pushed a commit that referenced this pull request Oct 23, 2026
…backs (#37895)

## Summary

`new ResizeObserver(() => ref.current)` and `new MutationObserver(() =>
ref.current)` currently report a false positive:

```
Error: Cannot access refs during render
  > 6 |   return new ResizeObserver(() => ref.current);
      |                             ^^^^^^^^^^^^^^^^^ Passing a ref to a function may read its value during render
```

Both constructors only *retain* the callback and invoke it
asynchronously after the observation fires — never during render — so
reading a ref inside the callback is safe. The same reasoning was
applied to `IntersectionObserver` in #37764; the remaining two DOM
observer constructors were still unmodeled and fell back to the default
effects for unknown constructors.

This PR models both the same way in the TypeScript and Rust compilers:

- `ResizeObserver(callback)`: single `Freeze`d callback. (Unlike
`IntersectionObserver`, whose options object is a second constructor
argument, the `{box}` option of `ResizeObserver` belongs to
`observe(target, options)`.)
- `MutationObserver(callback)`: single `Freeze`d callback.

## Validation

- `allow-ref-access-in-resize-observer.ts`: plain callback compiles, and
`observe(target, {box})` options do not trip the validation.
- `allow-ref-access-in-mutation-observer.ts`: callback compiles.
- `error.invalid-mutate-hook-value-in-resize-observer.js`: mutating a
`useMemo` value inside the callback is **still** rejected (`This value
cannot be modified`), i.e. the `Freeze` effect is preserved and only the
ref false positive is removed.
- Unknown constructors are unaffected: `new Observer(() => ref.current)`
still errors.
- Full fixture suite: 1835 fixtures, 25 changed / 3 failed — identical
to the pre-existing baseline in this environment (`fbt/*`, `debugger*`,
`conflict-codegen-instrument-forget`), so no new snapshot deltas.
- `tsc --noEmit` and `prettier check-changed` pass.

## Notes

The observers' instance methods (`observe`/`unobserve`/`disconnect`) are
intentionally left unmodeled, matching `IntersectionObserver`.

Co-authored-by: zhoubiao188 <[email protected]>
github-actions Bot pushed a commit that referenced this pull request Oct 23, 2026
…backs (#37895)

## Summary

`new ResizeObserver(() => ref.current)` and `new MutationObserver(() =>
ref.current)` currently report a false positive:

```
Error: Cannot access refs during render
  > 6 |   return new ResizeObserver(() => ref.current);
      |                             ^^^^^^^^^^^^^^^^^ Passing a ref to a function may read its value during render
```

Both constructors only *retain* the callback and invoke it
asynchronously after the observation fires — never during render — so
reading a ref inside the callback is safe. The same reasoning was
applied to `IntersectionObserver` in #37764; the remaining two DOM
observer constructors were still unmodeled and fell back to the default
effects for unknown constructors.

This PR models both the same way in the TypeScript and Rust compilers:

- `ResizeObserver(callback)`: single `Freeze`d callback. (Unlike
`IntersectionObserver`, whose options object is a second constructor
argument, the `{box}` option of `ResizeObserver` belongs to
`observe(target, options)`.)
- `MutationObserver(callback)`: single `Freeze`d callback.

## Validation

- `allow-ref-access-in-resize-observer.ts`: plain callback compiles, and
`observe(target, {box})` options do not trip the validation.
- `allow-ref-access-in-mutation-observer.ts`: callback compiles.
- `error.invalid-mutate-hook-value-in-resize-observer.js`: mutating a
`useMemo` value inside the callback is **still** rejected (`This value
cannot be modified`), i.e. the `Freeze` effect is preserved and only the
ref false positive is removed.
- Unknown constructors are unaffected: `new Observer(() => ref.current)`
still errors.
- Full fixture suite: 1835 fixtures, 25 changed / 3 failed — identical
to the pre-existing baseline in this environment (`fbt/*`, `debugger*`,
`conflict-codegen-instrument-forget`), so no new snapshot deltas.
- `tsc --noEmit` and `prettier check-changed` pass.

## Notes

The observers' instance methods (`observe`/`unobserve`/`disconnect`) are
intentionally left unmodeled, matching `IntersectionObserver`.

Co-authored-by: zhoubiao188 <[email protected]>

DiffTrain build for [23cd68d](23cd68d)
github-actions Bot pushed a commit that referenced this pull request Oct 23, 2026
…backs (#37895)

## Summary

`new ResizeObserver(() => ref.current)` and `new MutationObserver(() =>
ref.current)` currently report a false positive:

```
Error: Cannot access refs during render
  > 6 |   return new ResizeObserver(() => ref.current);
      |                             ^^^^^^^^^^^^^^^^^ Passing a ref to a function may read its value during render
```

Both constructors only *retain* the callback and invoke it
asynchronously after the observation fires — never during render — so
reading a ref inside the callback is safe. The same reasoning was
applied to `IntersectionObserver` in #37764; the remaining two DOM
observer constructors were still unmodeled and fell back to the default
effects for unknown constructors.

This PR models both the same way in the TypeScript and Rust compilers:

- `ResizeObserver(callback)`: single `Freeze`d callback. (Unlike
`IntersectionObserver`, whose options object is a second constructor
argument, the `{box}` option of `ResizeObserver` belongs to
`observe(target, options)`.)
- `MutationObserver(callback)`: single `Freeze`d callback.

## Validation

- `allow-ref-access-in-resize-observer.ts`: plain callback compiles, and
`observe(target, {box})` options do not trip the validation.
- `allow-ref-access-in-mutation-observer.ts`: callback compiles.
- `error.invalid-mutate-hook-value-in-resize-observer.js`: mutating a
`useMemo` value inside the callback is **still** rejected (`This value
cannot be modified`), i.e. the `Freeze` effect is preserved and only the
ref false positive is removed.
- Unknown constructors are unaffected: `new Observer(() => ref.current)`
still errors.
- Full fixture suite: 1835 fixtures, 25 changed / 3 failed — identical
to the pre-existing baseline in this environment (`fbt/*`, `debugger*`,
`conflict-codegen-instrument-forget`), so no new snapshot deltas.
- `tsc --noEmit` and `prettier check-changed` pass.

## Notes

The observers' instance methods (`observe`/`unobserve`/`disconnect`) are
intentionally left unmodeled, matching `IntersectionObserver`.

Co-authored-by: zhoubiao188 <[email protected]>

DiffTrain build for [23cd68d](23cd68d)
javache pushed a commit that referenced this pull request Oct 26, 2026
…efs false positive (#37970)

Fixes #37955

**Depends on #37975** (retains declared `Freeze` effects for
already-frozen values, as suggested by @javache). Until that merges this
PR's diff also shows its commit.

## Summary

`react-hooks/refs` reports "Passing a ref to a function may read its
value during render" for callbacks passed to React Native's
`PanResponder.create({...})`, because the compiler treats `PanResponder`
imported from `react-native` as an unknown function that may call its
arguments during render. `PanResponder.create()` only stores the
handlers and invokes them later from gesture events.

The compiler already has a signature for exactly this
(`PanResponder.create` freezes its config and doesn't call it during
render), but it only exists in the test-only `shared-runtime` type
provider in `snap`, so real code never gets it. This adds the same
signature for `react-native` to `defaultModuleTypeProvider` (TypeScript,
and the Rust port in `default_module_type_provider.rs`), so the
callbacks are treated as deferred, like the `IntersectionObserver` fix
in #37764.

Other unknown functions still report errors when given ref-accessing
callbacks.

## How did you test this change?

Added a valid case to
`packages/eslint-plugin-react-hooks/__tests__/ReactCompilerRuleTypescript-test.ts`
(the repro shape from the issue). Snap fixtures can't cover this because
`snap` replaces the module type provider with its own.

- Without the fix: `cd packages/eslint-plugin-react-hooks && npx jest
ReactCompilerRuleTypescript` → `1 failed, 15 passed` (the new case).
- With the fix: `yarn build:compiler && npx jest` in
`packages/eslint-plugin-react-hooks` → `4 suites passed, 5087 tests
passed`.
- `yarn workspace babel-plugin-react-compiler tsc --noEmit` and `lint`
(in `compiler/`) pass; `yarn lint` at the root passes; prettier check
passes on the changed TS files.
- `cargo check -p react_compiler_hir` and `cargo fmt --check` pass for
the Rust change (I did not run the Rust test suite).
- `yarn snap` in `compiler/`: identical results with and without this
change (1812 passed, 20 failed; the failures are pre-existing, mostly
fbt fixtures in my local setup).
- Also added a memoized-config case (`useMemo` config passed to
`PanResponder.create`); with #37975 the eslint-plugin suite passes (5088
tests).
- `yarn flow` not run: the change touches no Flow-typed code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
github-actions Bot pushed a commit that referenced this pull request Oct 26, 2026
…efs false positive (#37970)

Fixes #37955

**Depends on #37975** (retains declared `Freeze` effects for
already-frozen values, as suggested by @javache). Until that merges this
PR's diff also shows its commit.

## Summary

`react-hooks/refs` reports "Passing a ref to a function may read its
value during render" for callbacks passed to React Native's
`PanResponder.create({...})`, because the compiler treats `PanResponder`
imported from `react-native` as an unknown function that may call its
arguments during render. `PanResponder.create()` only stores the
handlers and invokes them later from gesture events.

The compiler already has a signature for exactly this
(`PanResponder.create` freezes its config and doesn't call it during
render), but it only exists in the test-only `shared-runtime` type
provider in `snap`, so real code never gets it. This adds the same
signature for `react-native` to `defaultModuleTypeProvider` (TypeScript,
and the Rust port in `default_module_type_provider.rs`), so the
callbacks are treated as deferred, like the `IntersectionObserver` fix
in #37764.

Other unknown functions still report errors when given ref-accessing
callbacks.

## How did you test this change?

Added a valid case to
`packages/eslint-plugin-react-hooks/__tests__/ReactCompilerRuleTypescript-test.ts`
(the repro shape from the issue). Snap fixtures can't cover this because
`snap` replaces the module type provider with its own.

- Without the fix: `cd packages/eslint-plugin-react-hooks && npx jest
ReactCompilerRuleTypescript` → `1 failed, 15 passed` (the new case).
- With the fix: `yarn build:compiler && npx jest` in
`packages/eslint-plugin-react-hooks` → `4 suites passed, 5087 tests
passed`.
- `yarn workspace babel-plugin-react-compiler tsc --noEmit` and `lint`
(in `compiler/`) pass; `yarn lint` at the root passes; prettier check
passes on the changed TS files.
- `cargo check -p react_compiler_hir` and `cargo fmt --check` pass for
the Rust change (I did not run the Rust test suite).
- `yarn snap` in `compiler/`: identical results with and without this
change (1812 passed, 20 failed; the failures are pre-existing, mostly
fbt fixtures in my local setup).
- Also added a memoized-config case (`useMemo` config passed to
`PanResponder.create`); with #37975 the eslint-plugin suite passes (5088
tests).
- `yarn flow` not run: the change touches no Flow-typed code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>

DiffTrain build for [9ca7a27](9ca7a27)
github-actions Bot pushed a commit that referenced this pull request Oct 26, 2026
…efs false positive (#37970)

Fixes #37955

**Depends on #37975** (retains declared `Freeze` effects for
already-frozen values, as suggested by @javache). Until that merges this
PR's diff also shows its commit.

## Summary

`react-hooks/refs` reports "Passing a ref to a function may read its
value during render" for callbacks passed to React Native's
`PanResponder.create({...})`, because the compiler treats `PanResponder`
imported from `react-native` as an unknown function that may call its
arguments during render. `PanResponder.create()` only stores the
handlers and invokes them later from gesture events.

The compiler already has a signature for exactly this
(`PanResponder.create` freezes its config and doesn't call it during
render), but it only exists in the test-only `shared-runtime` type
provider in `snap`, so real code never gets it. This adds the same
signature for `react-native` to `defaultModuleTypeProvider` (TypeScript,
and the Rust port in `default_module_type_provider.rs`), so the
callbacks are treated as deferred, like the `IntersectionObserver` fix
in #37764.

Other unknown functions still report errors when given ref-accessing
callbacks.

## How did you test this change?

Added a valid case to
`packages/eslint-plugin-react-hooks/__tests__/ReactCompilerRuleTypescript-test.ts`
(the repro shape from the issue). Snap fixtures can't cover this because
`snap` replaces the module type provider with its own.

- Without the fix: `cd packages/eslint-plugin-react-hooks && npx jest
ReactCompilerRuleTypescript` → `1 failed, 15 passed` (the new case).
- With the fix: `yarn build:compiler && npx jest` in
`packages/eslint-plugin-react-hooks` → `4 suites passed, 5087 tests
passed`.
- `yarn workspace babel-plugin-react-compiler tsc --noEmit` and `lint`
(in `compiler/`) pass; `yarn lint` at the root passes; prettier check
passes on the changed TS files.
- `cargo check -p react_compiler_hir` and `cargo fmt --check` pass for
the Rust change (I did not run the Rust test suite).
- `yarn snap` in `compiler/`: identical results with and without this
change (1812 passed, 20 failed; the failures are pre-existing, mostly
fbt fixtures in my local setup).
- Also added a memoized-config case (`useMemo` config passed to
`PanResponder.create`); with #37975 the eslint-plugin suite passes (5088
tests).
- `yarn flow` not run: the change touches no Flow-typed code.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>

DiffTrain build for [9ca7a27](9ca7a27)
javache pushed a commit that referenced this pull request Oct 26, 2026
…r callbacks (#37996)

## Summary

`new PerformanceObserver(cb)` and `new ReportingObserver(cb)` are
compiled with a false positive when the callback touches a ref:

```
Error: Cannot access refs during render
  4 |   return new PerformanceObserver(() => {
    |                                  ^^^^^^^^^^^^^^ Passing a ref to a function may read its value during render
```

Both constructors only *retain* the callback and invoke it
asynchronously once the observation fires — never during render — so
reading (or writing) a ref from the callback is safe.
`IntersectionObserver` (#37764) and `ResizeObserver` /
`MutationObserver` (#37895) are already modelled exactly this way; these
two were just missed and fall back to the unknown-constructor default,
whose `Freeze` on the callback trips `ValidateNoRefAccessInRender`.

This is the same class of fix as #37895, which is now on `main`.

## Fix

Add both to `TYPED_GLOBALS` (TypeScript) and `build_typed_globals`
(Rust) using the same signature shape as the existing observers:

| Global | Constructor signature |
| --- | --- |
| `PerformanceObserver` | `(callback)` → `[Freeze]` |
| `ReportingObserver` | `(callback, options)` → `[Freeze, Read]` |

`ReportingObserver`'s second argument is a genuine constructor argument
(unlike the observers whose options belong to `observe()`), so it is
read rather than retained.

Both backends are updated so TS and Rust stay in parity.

## Tests

Four new fixtures:

- `allow-ref-access-in-performance-observer.ts`
- `allow-ref-access-in-reporting-observer.ts`

Both fail before the change with `Cannot access refs during render` and
compile to memoized constructors after it.

- `error.invalid-mutate-hook-value-in-performance-observer.js`
- `error.invalid-mutate-hook-value-in-reporting-observer.js`

Negative controls proving `Freeze` is not weakened: mutating a `useMemo`
value inside the callback still reports `` `entries` cannot be modified
``.

Validation run locally:

- Full fixture suite (1840 fixtures): `25 changed / 3 failed` —
identical to the pre-existing baseline (`fbt/*`, `debugger*`), no new
diffs.
- `tsc --noEmit`, `eslint src`, `prettier check-changed` all clean.
- Rust side mirrors the TS change 1:1 but was not compiled locally (no
toolchain in this environment); relying on the
`babel-plugin-react-compiler-rust` CI job.

Co-authored-by: zhoubiao188 <[email protected]>
github-actions Bot pushed a commit that referenced this pull request Oct 26, 2026
…r callbacks (#37996)

## Summary

`new PerformanceObserver(cb)` and `new ReportingObserver(cb)` are
compiled with a false positive when the callback touches a ref:

```
Error: Cannot access refs during render
  4 |   return new PerformanceObserver(() => {
    |                                  ^^^^^^^^^^^^^^ Passing a ref to a function may read its value during render
```

Both constructors only *retain* the callback and invoke it
asynchronously once the observation fires — never during render — so
reading (or writing) a ref from the callback is safe.
`IntersectionObserver` (#37764) and `ResizeObserver` /
`MutationObserver` (#37895) are already modelled exactly this way; these
two were just missed and fall back to the unknown-constructor default,
whose `Freeze` on the callback trips `ValidateNoRefAccessInRender`.

This is the same class of fix as #37895, which is now on `main`.

## Fix

Add both to `TYPED_GLOBALS` (TypeScript) and `build_typed_globals`
(Rust) using the same signature shape as the existing observers:

| Global | Constructor signature |
| --- | --- |
| `PerformanceObserver` | `(callback)` → `[Freeze]` |
| `ReportingObserver` | `(callback, options)` → `[Freeze, Read]` |

`ReportingObserver`'s second argument is a genuine constructor argument
(unlike the observers whose options belong to `observe()`), so it is
read rather than retained.

Both backends are updated so TS and Rust stay in parity.

## Tests

Four new fixtures:

- `allow-ref-access-in-performance-observer.ts`
- `allow-ref-access-in-reporting-observer.ts`

Both fail before the change with `Cannot access refs during render` and
compile to memoized constructors after it.

- `error.invalid-mutate-hook-value-in-performance-observer.js`
- `error.invalid-mutate-hook-value-in-reporting-observer.js`

Negative controls proving `Freeze` is not weakened: mutating a `useMemo`
value inside the callback still reports `` `entries` cannot be modified
``.

Validation run locally:

- Full fixture suite (1840 fixtures): `25 changed / 3 failed` —
identical to the pre-existing baseline (`fbt/*`, `debugger*`), no new
diffs.
- `tsc --noEmit`, `eslint src`, `prettier check-changed` all clean.
- Rust side mirrors the TS change 1:1 but was not compiled locally (no
toolchain in this environment); relying on the
`babel-plugin-react-compiler-rust` CI job.

Co-authored-by: zhoubiao188 <[email protected]>

DiffTrain build for [c050dbd](c050dbd)
github-actions Bot pushed a commit that referenced this pull request Oct 26, 2026
…r callbacks (#37996)

## Summary

`new PerformanceObserver(cb)` and `new ReportingObserver(cb)` are
compiled with a false positive when the callback touches a ref:

```
Error: Cannot access refs during render
  4 |   return new PerformanceObserver(() => {
    |                                  ^^^^^^^^^^^^^^ Passing a ref to a function may read its value during render
```

Both constructors only *retain* the callback and invoke it
asynchronously once the observation fires — never during render — so
reading (or writing) a ref from the callback is safe.
`IntersectionObserver` (#37764) and `ResizeObserver` /
`MutationObserver` (#37895) are already modelled exactly this way; these
two were just missed and fall back to the unknown-constructor default,
whose `Freeze` on the callback trips `ValidateNoRefAccessInRender`.

This is the same class of fix as #37895, which is now on `main`.

## Fix

Add both to `TYPED_GLOBALS` (TypeScript) and `build_typed_globals`
(Rust) using the same signature shape as the existing observers:

| Global | Constructor signature |
| --- | --- |
| `PerformanceObserver` | `(callback)` → `[Freeze]` |
| `ReportingObserver` | `(callback, options)` → `[Freeze, Read]` |

`ReportingObserver`'s second argument is a genuine constructor argument
(unlike the observers whose options belong to `observe()`), so it is
read rather than retained.

Both backends are updated so TS and Rust stay in parity.

## Tests

Four new fixtures:

- `allow-ref-access-in-performance-observer.ts`
- `allow-ref-access-in-reporting-observer.ts`

Both fail before the change with `Cannot access refs during render` and
compile to memoized constructors after it.

- `error.invalid-mutate-hook-value-in-performance-observer.js`
- `error.invalid-mutate-hook-value-in-reporting-observer.js`

Negative controls proving `Freeze` is not weakened: mutating a `useMemo`
value inside the callback still reports `` `entries` cannot be modified
``.

Validation run locally:

- Full fixture suite (1840 fixtures): `25 changed / 3 failed` —
identical to the pre-existing baseline (`fbt/*`, `debugger*`), no new
diffs.
- `tsc --noEmit`, `eslint src`, `prettier check-changed` all clean.
- Rust side mirrors the TS change 1:1 but was not compiled locally (no
toolchain in this environment); relying on the
`babel-plugin-react-compiler-rust` CI job.

Co-authored-by: zhoubiao188 <[email protected]>

DiffTrain build for [c050dbd](c050dbd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug: react-hooks/refs false positive using IntersectionObserver

2 participants