Skip to content

fix: ensure tracking is paused when emit() calls handler so it can safely be called in effects (fix #6669) #6688

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

LinusBorg
Copy link
Member

@LinusBorg LinusBorg commented Sep 17, 2022

fix: #13338
fix: #6669

If emit() is called in an effect (i.e. the callback of a watchEffect), it will collect any reactive values accessed in that parent handle as dependencies of the current component.

This can lead to a recursive loop crashing the app.

Summary by CodeRabbit

  • Bug Fixes

    • Improved event handling to prevent unintended reactive tracking during event listener execution, reducing the risk of infinite loops or repeated triggers.
  • Tests

    • Added a new test case to ensure event listeners do not cause unwanted reactive effects.

@LinusBorg LinusBorg force-pushed the linusborg/pause-tracking-in-emit-6669 branch from 09f17b4 to 1c02e5a Compare September 17, 2022 10:00
@edison1105
Copy link
Member

I feel this PR is necessary though ##6669 is closed.

@LinusBorg
Copy link
Member Author

@yyx990803 You closed #6669 as "not a bug", so I assume my PR can be closed?

@skirtles-code
Copy link
Contributor

skirtles-code commented May 31, 2024

Just in case this does get merged, I think the same change would need to be applied to the onceHandler a bit further down.


As for whether it should be merged, I'm very much on the fence.

I think it's an easy problem for people to fall into without really understanding what's going on.

The exact timing of operations in Vue is not generally well understood by users. Various things are sensitive to timing and it usually 'just works' without needing to think about it.

I don't think it's necessarily obvious that emit runs code synchronously in the parent. I've encountered a lot of people who seem to think it's asynchronous. Why? Because the child emits an update event and the child's props don't synchronously update. They conclude that it's because the 'message' (event) is delivered asynchronously to the parent.

Even if someone isn't thinking about it in quite those terms, I still think events are perceived as somehow different from normal function calls, like throwing a parcel over a wall and not having to worry about what's on the other side.

But, I can also see Evan's perspective for closing the original issue.


Update: A few days after I posted this, we had another conversation about the synchronicity of emit on Vue Land. Link. On this occasion, two participants in the conversation believed that emit is not synchronous, Quote: emit is fired on the microtask. Perhaps this needs to be addressed more explicitly in the docs?

@edison1105 edison1105 closed this Oct 21, 2024
@edison1105 edison1105 deleted the linusborg/pause-tracking-in-emit-6669 branch October 21, 2024 07:37
@edison1105 edison1105 restored the linusborg/pause-tracking-in-emit-6669 branch October 21, 2024 08:22
@edison1105 edison1105 reopened this Oct 21, 2024
@edison1105 edison1105 added the 🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. label May 17, 2025
Copy link

coderabbitai bot commented May 17, 2025

Walkthrough

The changes introduce reactivity tracking control in the Vue emit function by pausing and resetting tracking around event handler invocations. A new test verifies that emitting events inside a reactive effect does not cause infinite loops or repeated triggers due to unintended dependency tracking during event listener execution.

Changes

File(s) Change Summary
packages/runtime-core/__tests__/componentEmits.spec.ts Added a test ensuring no reactive tracking occurs during event listener execution to prevent loops.
packages/runtime-core/src/componentEmits.ts Wrapped event handler invocation in pauseTracking() and resetTracking() to control reactivity.

Sequence Diagram(s)

sequenceDiagram
    participant Component
    participant EmitFunction
    participant EventHandler
    participant Reactivity

    Component->>EmitFunction: emit('event', ...)
    EmitFunction->>Reactivity: pauseTracking()
    EmitFunction->>EventHandler: callWithAsyncErrorHandling()
    EventHandler-->>EmitFunction: (event handled)
    EmitFunction->>Reactivity: resetTracking()
    EmitFunction-->>Component: (done)
Loading

Assessment against linked issues

Objective Addressed Explanation
Prevent watchEffect from collecting dependencies on emits and causing infinite/reactive loops (#13338, #6669)

Poem

A bunny hopped through code so neat,
Ensuring emits and effects don’t repeat.
With tracking paused and bugs at bay,
Reactive loops are kept away.
Now tests confirm the fix is right—
No more infinite loops in sight!
🐇✨

✨ 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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 1222437 and 1c02e5a.

📒 Files selected for processing (2)
  • packages/runtime-core/__tests__/componentEmits.spec.ts (2 hunks)
  • packages/runtime-core/src/componentEmits.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/runtime-core/__tests__/componentEmits.spec.ts (1)
packages/runtime-core/src/componentEmits.ts (1)
  • emit (73-195)
🔇 Additional comments (3)
packages/runtime-core/src/componentEmits.ts (1)

30-30: Appropriate import for tracking control.

The added import brings in reactivity tracking control methods, which will be used to pause dependency tracking during event handler execution.

packages/runtime-core/__tests__/componentEmits.spec.ts (2)

10-12: Added necessary imports for reactive testing.

These imports are required for the new test case that verifies the reactivity tracking behavior.


437-467: Well-designed test for the reactivity tracking fix.

This test effectively verifies that event handlers aren't being tracked as dependencies of reactive effects. By using a watchEffect that emits an event, and an event handler that modifies reactive state and triggers multiple ticks, it confirms that the counter only increments once instead of causing an infinite loop.

The test design aligns perfectly with the fix implemented in componentEmits.ts by proving that reactive tracking is properly paused during handler execution.

Comment on lines +165 to +172
pauseTracking()
callWithAsyncErrorHandling(
handler,
instance,
ErrorCodes.COMPONENT_EVENT_HANDLER,
args
)
resetTracking()
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Good fix: Pausing reactivity tracking during event handler execution.

This change prevents reactive dependencies from being tracked while executing event handlers called through emit(). This fixes issue #6669 where emitting events inside an effect could cause infinite loops when reactive state was accessed inside the event handlers.

However, the same fix should be applied to the onceHandler code block (lines 175-189) to maintain consistency.

  if (onceHandler) {
    if (!instance.emitted) {
      instance.emitted = {} as Record<any, boolean>
    } else if (instance.emitted[handlerName]) {
      return
    }
    instance.emitted[handlerName] = true
+   pauseTracking()
    callWithAsyncErrorHandling(
      onceHandler,
      instance,
      ErrorCodes.COMPONENT_EVENT_HANDLER,
      args
    )
+   resetTracking()
  }
🤖 Prompt for AI Agents
In packages/runtime-core/src/componentEmits.ts between lines 175 and 189, apply
the same pauseTracking and resetTracking calls around the onceHandler invocation
as done for the regular handler at lines 165-172. This ensures reactive
dependencies are not tracked during the execution of onceHandler event
callbacks, preventing infinite loops and maintaining consistency in event
handling.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
🔨 p3-minor-bug Priority 3: this fixes a bug, but is an edge case that only affects very specific usage. need discussion
Projects
Status: Needs Review
Development

Successfully merging this pull request may close these issues.

watchEffect performs bad with emits watchEffect should not have side effects on the response in emits
3 participants