Skip to content

$watch can fire after being unwatched when Livewire's morph removes its element #4902

Closed

Description

@MaxencePaulin

Alpine.js version

3.17.2

Browser and operating system

Brave on Windows

Describe the issue you're experiencing

When an Alpine component using $watch (or Livewire's $wire.$watch) is removed from the page, a change to a value it was watching can still run the watch callback once, even though the component is already gone.

In a Livewire app this shows up when a component is removed by a morph (e.g. a wire:key change, an @if toggling off, a list item disappearing) in the same request that also updated a property the component was watching with $wire.$watch (like resetting it). The callback still fires one extra time for an Alpine component that's already been removed from the page, which can throw errors.

A workaround would be to store a destroyed state set to true in the hooked destroy() function, and check it in every watched callback, but I think this can be fixed directly in the package.

Code snippets to reproduce the issue

Click the button. It removes the inner element and after that it changes foo. calls becomes 1.

<div x-data="{ calls: 0 }">
    <div
        x-data="{ foo: 'bar' }"
        x-init="$watch('foo', () => { calls++ })"
    >
        <button x-on:click="$root.remove(); foo = 'baz'"></button>
    </div>

    <span x-text="calls"></span>
</div>

Screenshots/screen recordings

//

How do you expect it to work?

calls should stay 0. The element is removed first, then foo changes, so $watch shouldn't fire for a change made after its element was already removed.

Please confirm (incomplete submissions will not be addressed)

  • I have provided easy and step-by-step instructions to reproduce the bug.
  • I have provided code samples as text and NOT images.
  • I understand my bug report will be removed if I haven't met the criteria above.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions