Skip to content

feat(compiler-core): warn instead of assign for v-model on reactive on reactive objects (fix #13693) - #13694

Closed
Ray-D-Song wants to merge 1 commit into
vuejs:mainfrom
Ray-D-Song:main
Closed

Ray-D-Song wants to merge 1 commit into
vuejs:mainfrom
Ray-D-Song:main

Conversation

@Ray-D-Song

@Ray-D-Song Ray-D-Song commented Jul 23, 2025 •

Copy link
Copy Markdown

This PR fixes a compatibility issue with rolldown bundler and prevents potential runtime errors by replacing assignment statements with warnings when v-model is used directly on reactive objects.

Problem Statement

When using v-model directly on reactive objects in <script setup>, Vue's compiler generates assignment code that attempts to reassign const variables:

<script setup>
const form = reactive({ name: 'John', age: 25 })
</script>

<template>
  <!-- This generates: $event => ((form) = $event) -->
  <Form v-model="form" />
</template>

Generated problematic code:

"onUpdate:modelValue": $event => ((form) = $event)

This causes several issues:

  1. Rolldown Build Failures: Triggers ILLEGAL_REASSIGNMENT errors in rolldown-based Vite builds
  2. Potential Runtime Errors: If the assignment were executed, it would fail at runtime
  3. Silent Bugs: The pattern "works" only because child components use useModel() proxies instead of the parent's update handler

Why this worked before:

  • Rollup only checks const reassignment within the same scope
  • Vue's compilation separates variable declaration and update handlers into different scopes
  • Child components bypass the problematic assignment via useModel() proxies

Why it fails now:

  • Rolldown performs stricter cross-scope const reassignment checks
  • The generated assignment code is technically invalid, even if not executed

Solution

Replace the problematic assignment with a warning that guides developers toward correct usage:

Before:

"onUpdate:modelValue": $event => ((form) = $event)

After:

"onUpdate:modelValue": $event => (_warn("v-model cannot be used on reactive objects directly.", "Detected v-model on reactive variable 'form'. Consider using a reactive property or ref instead."), form)

Examples

<Form v-model="reactiveState" />  <!-- Generates warning -->
<Form v-model="reactiveState.field" />  <!-- Normal assignment -->
<input v-model="reactiveState['key']" />  <!-- Normal assignment -->

Summary by CodeRabbit

  • New Features

    • Added a runtime warning when using v-model directly on reactive constant variables, guiding users to use a reactive property or ref instead.
  • Bug Fixes

    • Ensured that using v-model on a property of a reactive constant variable does not trigger the new warning.
  • Tests

    • Introduced tests to verify the new warning behavior and confirm correct handling of member expressions with v-model.

@coderabbitai

coderabbitai Bot commented Jul 23, 2025 •

Copy link
Copy Markdown

Walkthrough

The changes introduce a new runtime warning mechanism for improper usage of v-model on reactive constant variables in the compiler core. This includes adding a warning helper, updating the vModel transform to emit warnings in specific cases, and adding corresponding tests to verify this behavior. No changes were made to exported function signatures.

Changes

File(s) Change Summary
packages/compiler-core/src/runtimeHelpers.ts Added WARN symbol constant and mapped it in helperNameMap.
packages/compiler-core/src/transforms/vModel.ts Imported WARN, updated vModel transform to emit warning via WARN for SETUP_REACTIVE_CONST identifiers.
packages/compiler-core/tests/transforms/vModel.spec.ts Added tests for warning emission and correct handler generation for v-model on reactive constants.

Estimated code review effort

2 (~15 minutes)

Suggested labels

ready to merge

Poem

A bunny hopped through compiler code,
Where warnings now are gently showed.
If v-model hugs a reactive friend,
A warning nudge we kindly send.
With tests to check and helpers born,
The garden’s logic is less forlorn.
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c486536 and 8d86a40.

⛔ Files ignored due to path filters (1)
  • packages/compiler-core/__tests__/transforms/__snapshots__/vModel.spec.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (3)
  • packages/compiler-core/__tests__/transforms/vModel.spec.ts (1 hunks)
  • packages/compiler-core/src/runtimeHelpers.ts (2 hunks)
  • packages/compiler-core/src/transforms/vModel.ts (3 hunks)
🧬 Code Graph Analysis (1)
packages/compiler-core/src/transforms/vModel.ts (4)
packages/compiler-core/src/utils.ts (2)
  • isMemberExpression (186-189)
  • isSimpleIdentifier (67-68)
packages/compiler-core/src/index.ts (1)
  • BindingTypes (11-11)
packages/compiler-core/src/runtimeHelpers.ts (1)
  • WARN (83-83)
packages/compiler-core/src/ast.ts (1)
  • createCompoundExpression (713-722)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/compiler-core/src/transforms/vModel.ts (4)
packages/compiler-core/src/utils.ts (2)
  • isMemberExpression (186-189)
  • isSimpleIdentifier (67-68)
packages/compiler-core/src/index.ts (1)
  • BindingTypes (11-11)
packages/compiler-core/src/runtimeHelpers.ts (1)
  • WARN (83-83)
packages/compiler-core/src/ast.ts (1)
  • createCompoundExpression (713-722)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Redirect rules
  • GitHub Check: Header rules
  • GitHub Check: Pages changed
🔇 Additional comments (8)
packages/compiler-core/src/runtimeHelpers.ts (2)

83-83: LGTM! Consistent helper symbol definition.

The new WARN helper symbol follows the established pattern and is correctly conditionally named for development mode.


127-127: LGTM! Proper helper mapping.

The mapping entry correctly associates the WARN symbol with the string "warn" for runtime helper resolution during code generation.

packages/compiler-core/src/transforms/vModel.ts (4)

19-19: LGTM! Correct import addition.

The WARN helper is properly imported and will be used for generating runtime warnings.


58-68: LGTM! Proper validation logic extension.

The validation logic correctly allows SETUP_REACTIVE_CONST binding type, enabling the new warning behavior while maintaining existing validation for other cases.


110-121: LGTM! Well-implemented warning mechanism.

The new conditional branch correctly:

  • Detects reactive const simple identifiers (not member expressions)
  • Registers the WARN helper for code generation
  • Generates a clear, actionable warning message
  • Returns the reactive object unchanged instead of attempting assignment

This properly addresses the Rollup compatibility issue described in the PR objectives.


110-121: No action needed: warn helper is properly exported
I’ve confirmed that:

  • packages/compiler-core/src/runtimeHelpers.ts defines the WARN helper symbol mapped to "warn".
  • packages/runtime-core/src/index.ts exports warn for runtime use.

The generated context.helper(WARN) will correctly import the warn API from Vue at runtime.

packages/compiler-core/__tests__/transforms/vModel.spec.ts (2)

586-615: LGTM! Comprehensive test for reactive const warning.

The test properly verifies:

  • Correct binding metadata setup
  • Warning helper call generation in the update handler
  • Proper warning message content
  • Snapshot verification for complete generated code

The test accurately covers the new warning behavior for direct reactive const usage.


617-645: LGTM! Important edge case test for member expressions.

This test correctly verifies that member expressions on reactive constants (e.g., reactiveVar.foo) do not trigger the warning and generate normal assignment handlers. This distinction is crucial for the feature's usability.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@Ray-D-Song Ray-D-Song changed the title feat(compiler-core): warn instead of assign for v-model on reactive on reactive objects (fix #13593) feat(compiler-core): warn instead of assign for v-model on reactive on reactive objects (fix #13693) Jul 23, 2025
@edison1105

Copy link
Copy Markdown
Member

Thank you for your PR, but this change is incorrect because we only show warnings in DEV.
I prefer #11275.

@edison1105 edison1105 closed this Jul 25, 2025
@Ray-D-Song

Copy link
Copy Markdown
Author

Thank you for your reply, but I have a question.
It seems that #11275 will continue to generate assignment statements for v-model on const variables, which doesn't solve the problem of rolldown ILLEGAL_REASSIGNMENT failing to bundle.
Did I miss something? I hope you can explain it. 🙏

Thank you for your PR, but this change is incorrect because we only show warnings in DEV. I prefer #11275.

@edison1105

edison1105 commented Jul 25, 2025 •

Copy link
Copy Markdown
Member

During the bundling phase, rolldown can emit warnings that are better than runtime warnings (perhaps compiler-core should do the same), allowing developers to detect issues earlier. By modifying the compilation result to remove rolldown's ILLEGAL_REASSIGNMENT error and moving the warning to runtime, this approach is unreasonable.

Both this PR and #11275 warn users at runtime about "Assignment to constant variable" in the code. Ultimately, users will need to adjust their code in either case.

@Ray-D-Song

Ray-D-Song commented Jul 25, 2025 •

Copy link
Copy Markdown
Author

I understand your point.
However, this also means that directly binding a reactive variable to v-model is not allowed.
Yet, there's no mention of this in the documentation, and many projects and libraries have adopted this approach (because it does work).
When Rolldown eventually becomes Vite's default bundler, these libraries will fail to bundle, because the bundler won't just print a warning, but will directly interrupt the bundling process with an error.

This is just my personal opinion, but v-model on reactive objects has become similar to undefined behavior in C compilers. I hope you can adopt a more compatible approach.

Thank you for your patience.❤️

This branch was successfully deployed

1 active deployment
Preview — 8d86a40a Deployed Jul 23, 2025 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants