Skip to content

Preserve action params for actions reading them asynchronously - #938

Open
tafax wants to merge 3 commits into
hotwired:mainfrom
tafax:fix-async-action-params
Open

tafax wants to merge 3 commits into
hotwired:mainfrom
tafax:fix-async-action-params

Conversation

@tafax

@tafax tafax commented Nov 24, 2026 •

Copy link
Copy Markdown

The problem

Stimulus attaches action params to the native event with Object.assign(event, { params }). When the same event triggers more than one action, every action writes its params onto the same object, so event.params only holds the right values until the next action runs.

That's fine for synchronous actions. It breaks as soon as an action reads its params after an await, or inside a callback that runs later. By then the event has bubbled up and other actions have overwritten event.params.

We hit this in production with a setup like this:

<div data-controller="tabs menu">
  <a data-action="click->tabs#activate click@window->menu#closeOnClickOutside"
     data-tabs-url-param="/tabs/details">Details</a>
</div>

// tabs_controller.js
async activate({ params }) {        // destructured here: works
async activate(event) {
  await this.saveState()
  fetch(event.params.url)            // params are now {} from menu#closeOnClickOutside
}

menu#closeOnClickOutside has no params, so when it runs on window it resets event.params to {}. The tabs#activate action then reads an empty object after its await. The same thing happens with two actions on the same element, or with an action on an ancestor.

I think this is what #766 was about. It was closed because it couldn't be reproduced with synchronous actions, and the controller linked there reads params asynchronously.

The fix

prepareActionEvent now gives each action a Proxy of the native event that returns that action's own params. Everything else is forwarded to the original event. Methods are bound to it, so preventDefault(), stopPropagation() and friends keep working, and writes go through to it as well.

The params are still assigned to the native event too, so code that reads them synchronously from the raw event keeps working.

Trade-offs

A few things change because actions now receive a proxy instead of the event itself:

  • event in an action is no longer === to the native event
  • Re-dispatching it with element.dispatchEvent(event) throws a TypeError, because native APIs reject proxies. I couldn't find a real use for this, but it's a behavior change
  • event.preventDefault !== event.preventDefault, since methods are bound on every access. Easy to cache if it matters
  • [after the code review] Two actions triggered by the same event now receive two different objects, so identity checks across actions no longer match, e.g. a controller that skips its own opening click with event === this.openingEvent, or a WeakSet shared between actions. Flags like event.handled = true still work, since writes go through to the native event, and new event.constructor(event.type, event) still makes a copy that can be re-dispatched

If a proxy is too much, the other option I can see is passing params as a second argument to the action (activate(event, params)). That avoids the shared state completely, but it adds API surface. Happy to go that way if you prefer it.

Tests

I added LogController#logDeferred, which records the action after an await, plus two tests in action_params_tests.ts:

  • an async action followed by another action on the same element
  • an async action followed by a window action that has no params

Both fail on main and pass with this change.

@czj czj left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for digging this one out, the @window case explains #766 well. I ran the suite and a few extra probes in Chrome and Firefox: preventDefault(), stopPropagation(), stopImmediatePropagation(), composedPath(), getModifierState(), the :stop/:prevent options, instanceof and currentTarget all behave as on main through the proxy. I'd keep the proxy over a second argument: code that already reads event.params gets fixed without changes, and Object.create(event) isn't an option since type, target and preventDefault() all throw on it. Two small things inline, checked with the suite and the probes green in both browsers.

Comment thread src/core/binding.ts Outdated
return params
}
const value = Reflect.get(target, property, target)
return typeof value == "function" ? value.bind(target) : value

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This binds every function value, not only methods: event.constructor turns into bound PointerEvent, and a CustomEvent whose detail is a function no longer hands back that same function. Binding only methods (data properties, constructor aside) keeps both as on main:

Suggested change
return typeof value == "function" ? value.bind(target) : value
return typeof value == "function" && isMethod(target, property) ? value.bind(target) : value

with, at the bottom of the file:

function isMethod(object: object, property: PropertyKey): boolean {
  for (let current: object | null = object; current; current = Object.getPrototypeOf(current)) {
    const descriptor = Object.getOwnPropertyDescriptor(current, property)
    if (descriptor) return "value" in descriptor && property !== "constructor"
  }
  return false
}

Comment thread src/core/binding.ts Outdated

private prepareActionEvent(event: Event): ActionEvent {
return Object.assign(event, { params: this.action.params })
const { params } = this.action

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Needed by the next comment, so params can be reassigned:

Suggested change
const { params } = this.action
let { params } = this.action

Comment thread src/core/binding.ts
const value = Reflect.get(target, property, target)
return typeof value == "function" ? value.bind(target) : value
},
set(target, property, value) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

An action that assigns event.params = { ... } reads the old params back right after, since get always returns the captured ones (on main it reads the new value). Updating them here fixes it:

Suggested change
set(target, property, value) {
set(target, property, value) {
if (property === "params") {
params = value
}

@tafax
tafax requested a review from czj November 25, 2026 10:39

@czj czj left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for taking both on so quickly. On 0d3d80c each new test fails without its fix, and the suite passes locally in Chrome, Firefox and WebKit. The proxy adds 0.2 to 0.3 µs per action call in Chrome and Firefox and 0.8 µs in WebKit, against 1.8 to 2.5 µs per event on main (20k mousemove dispatches).

One more trade-off worth adding to the list in the description: two actions on the same event now receive two different objects, so a controller that skips its own opening click with event === this.openingEvent, or a WeakSet shared between actions, no longer matches. A flag such as event.handled = true still works, since writes go through to the native event, and new event.constructor(event.type, event) still makes a copy that can be re-dispatched.

One corner my isMethod suggestion missed, inline.

Comment thread src/core/binding.ts Outdated
function isMethod(object: object, property: PropertyKey): boolean {
for (let current: object | null = object; current; current = Object.getPrototypeOf(current)) {
const descriptor = Object.getOwnPropertyDescriptor(current, property)
if (descriptor) return "value" in descriptor && property !== "constructor"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

My suggestion missed one case: an own method defined with Object.defineProperty(event, "method", { value: fn }) is read-only and non-configurable by default, and a proxy has to return such a property unchanged, so reading event.method throws a TypeError where main returns fn. Rare, but easy to leave unbound:

Suggested change
if (descriptor) return "value" in descriptor && property !== "constructor"
if (descriptor) {
const frozen = current === object && !descriptor.writable && !descriptor.configurable
return "value" in descriptor && property !== "constructor" && !frozen
}

with a test in action_tests.ts, failing in Chrome, Firefox and WebKit without it:

  async "test the action event returns a read-only own method as is"() {
    const method = () => {}
    const event = new Event("click", { bubbles: true })
    Object.defineProperty(event, "method", { value: method })
    this.findElement("button").dispatchEvent(event)
    await this.nextFrame

    this.assert.strictEqual((this.actionLog[0].event as any).method, method)
  }

@tafax tafax Nov 25, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good catch. It's super rare, but I agree it's worth fixing. Applied, thanks.
I also added the trade-off to the list in the description.

@tafax
tafax requested a review from czj November 25, 2026 15:16

@czj czj left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks! c1fdc83 checked: the new test fails without the fix in Chrome and Firefox, and the full suite passes in both with it. LGTM.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants