From c5fa460784c41a2e09e9ed1c4468f4f089e2a78b Mon Sep 17 00:00:00 2001 From: Sathya Gunsasekaran Date: Thu, 25 Jul 2024 14:06:30 +0100 Subject: [PATCH] [compiler] Add tests for incorrect global mutation detection If a function expression that mutates a global is passed as a prop, we don't throw an error as we assume it's not called in render. But if this function expression is captured in an object and passed down as prop, we throw an error. ghstack-source-id: 74cacee09f565550007b2e01fa8877ad64ccfbe9 Pull Request resolved: https://github.com/facebook/react/pull/30456 --- ...r.object-capture-global-mutation.expect.md | 33 +++++++++++++++++++ .../error.object-capture-global-mutation.js | 12 +++++++ 2 files changed, 45 insertions(+) create mode 100644 compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.object-capture-global-mutation.expect.md create mode 100644 compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.object-capture-global-mutation.js diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.object-capture-global-mutation.expect.md b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.object-capture-global-mutation.expect.md new file mode 100644 index 0000000000..1ab2a46afe --- /dev/null +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.object-capture-global-mutation.expect.md @@ -0,0 +1,33 @@ + +## Input + +```javascript +function Foo() { + const x = () => { + window.href = 'foo'; + }; + const y = {x}; + return ; +} + +export const FIXTURE_ENTRYPOINT = { + fn: Foo, + params: [], +}; + +``` + + +## Error + +``` + 1 | function Foo() { + 2 | const x = () => { +> 3 | window.href = 'foo'; + | ^^^^^^ InvalidReact: Writing to a variable defined outside a component or hook is not allowed. Consider using an effect (3:3) + 4 | }; + 5 | const y = {x}; + 6 | return ; +``` + + \ No newline at end of file diff --git a/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.object-capture-global-mutation.js b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.object-capture-global-mutation.js new file mode 100644 index 0000000000..b3c936a2a2 --- /dev/null +++ b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.object-capture-global-mutation.js @@ -0,0 +1,12 @@ +function Foo() { + const x = () => { + window.href = 'foo'; + }; + const y = {x}; + return ; +} + +export const FIXTURE_ENTRYPOINT = { + fn: Foo, + params: [], +};