Fix x-ref crash during child-element morph#4748
Merged
calebporzio merged 1 commit intomainfrom Feb 16, 2026
Merged
Conversation
Wrap x-ref's inline handler with skipDuringClone() to prevent TypeError when morph runs on a child element (not the x-data root). During morph, cloneNode() runs directives on detached elements where closestRoot() returns undefined. Refs re-register on live DOM via MutationObserver. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
TypeError: Cannot read property '_x_refs' of undefinedwhen callingAlpine.morph()on a child element (not thex-dataroot) that containsx-refattributesx-ref's inline handler withskipDuringClone()— the established Alpine pattern used by 10+ other directives<section>containingx-refand verifies state preservation + ref resolutionProblem
When morphing a child element, morph's
cloneNode()runs directives on detachedtoelements whose parent chain has no[x-data]ancestor.closestRoot()returnsundefined, andx-refdereferences it → crash.This affects htmx+Alpine users in production (reported in #3797, #3758, #3003).
Why
skipDuringCloneover a null guardThe PR #4744 proposed
if (! root) return— a valid fix, butskipDuringCloneis the Alpine-established pattern for "this directive doesn't need to run during clone." Refs on detachedtoelements are discarded anyway; post-morph, refs re-register on live DOM via the MutationObserver path.Test plan
x-ref— no crash, state preserved,$refsresolves$refstests passCloses #3797. Alternative to #4744.
🤖 Generated with Claude Code