ReviewOS

stacks/stx

Event-handler auto-unwrap silently swallows TypeErrors when expression doesn't mention `.set(`

#1694
Closed glennmichael123 opened this 23 days ago · 0 comments
23 days ago

Summary

stx event handlers (@click / @input / etc.) decide whether to keep each in-scope signal "raw" or auto-unwrap it to its value based on a substring check of the expression text (signals.ts:1669):

if (v && typeof v === 'function' && v._isSignal && value.includes(k + '.set(')) {
  return 'var ' + k + ' = __s["' + k + '"]'        // keep as raw signal
}
return 'var ' + k + ' = … ? __s["' + k + '"]() : __s["' + k + '"]'  // auto-unwrap

When the click handler calls a helper function that does the .set() internally — instead of writing .set() directly in the expression — the detector misses it. The signal gets unwrapped to its value (e.g. null) in the handler's eval scope. The helper function then runs from its closure and (depending on how it accesses the signal) ends up throwing a TypeError.

The dispatcher's catch at signals.ts:1682 silently swallows TypeError and ReferenceError:

catch (e) {
  if (!(e instanceof ReferenceError) && !(e instanceof TypeError))
    console.warn('[STX] Handler error:', value, e)
}

→ No console warning. No visible effect. The click registers (event fired: click on … logs) but the app stays inert. Took ~30 minutes of bisecting to find.

Minimal repro

<script client>
  const picked = state(null)
  const items = state([{ id: 1, name: 'a' }, { id: 2, name: 'b' }])

  // Helper that does the .set() — common pattern when the logic is
  // non-trivial (multi-step state update, URL sync, etc.).
  function pick(item) {
    picked.set({ id: item.id, name: item.name })
  }
</script>

<ul>
  <li :for="item in items" @click="pick(item)">{{ item.name }}</li>
</ul>

<p :if="picked">Picked: {{ picked.name }}</p>

Expected: clicking an <li> updates picked, paragraph appears. Actual: [stx] event fired: click on LI logs, picked never updates, paragraph never appears, no warning.

The fix from the user's side is to put .set( literally in the expression text:

<li :for="item in items" @click="picked.set({ id: item.id, name: item.name })">…</li>

That works because value.includes('picked.set(') now matches. But this is the opposite of "keep complex logic in helper functions" — a normal refactoring step (@click="pickedAction(item)") silently breaks the binding.

Why it's hard to debug

  1. The error is swallowed. TypeError is in the explicit silent-throw list. There's no console warning, no overlay, no dev-mode hint.
  2. The trigger is non-local. The decision lives in the binder, evaluated based on what the user typed in the template. There's nothing in the helper function's source that explains why it behaves differently when called from @click vs called from anywhere else in JS.
  3. The pattern is encouraged elsewhere. All the docs / examples use named handlers (@click="handleSubmit()"). It's only when the handler modifies state through a closure-captured signal that this trips.
  4. The fix is non-obvious. "Mention .set( in the expression" is a workaround a user cannot derive from the symptom — they need to read the binder source.

Suggested fixes

Pick one (in order of how much I'd prefer them):

(a) Don't silently swallow TypeError / ReferenceError in handler dispatch

The original intent was probably "don't spam the console when expressions reference signals that haven't initialized yet" — but that's better solved by guarded lookups. At minimum, log the error in dev mode:

catch (e) {
  if (process.env.NODE_ENV !== 'production')
    console.error('[STX] Handler threw:', value, e)
}

This single change would have surfaced the bug immediately.

(b) Drop the substring-based "should unwrap?" decision

The current approach is fundamentally fragile — any function call that does .set() indirectly, any conditional, any helper, breaks the detection. Always keep signals raw in event handlers (require signalName() to read, like the rest of the runtime) — or always unwrap and require users to explicitly capture the raw signal when they want to call .set(). Either consistent rule beats heuristic substring matching.

(c) If keeping the substring detector, also match .set (no paren), method references (obj.signal.set), and helper-function inheritance

A simple AST walk over the expression body would catch all the cases. Faster than parsing-by-string but still keeps the convenience.

Bonus observation: cross-store derived chains don't propagate :if invalidation

Tangentially related — discovered in the same debug session. When a local derived() wraps a state signal from a different store:

const judgesStore = useStore('judges')
const results = derived(() => judgesStore.searchResults())   // ← local derived

// template:
<div :if="results.length > 0">…</div>

judgesStore.searchResults.set([…items]) correctly notifies its subscriber (the local derived), but the change doesn't bubble through to the :if effect. The dropdown stays hidden despite the source signal updating.

Worked around by collapsing the layer via an effect() that pushes to a local state:

const showResults = state(false)
effect(() => {
  showResults.set(judgesStore.searchResults().length > 0)
})
// template:
<div :if="showResults">…</div>

The effect() reads the cross-store signal directly, the local state is in the same module as the :if, no chain to drop the notification.

Same general theme: stx's reactivity is sound at one level but propagation across boundaries (event-handler / cross-store / derived-chain) has surprising gaps that should arguably be tracked as separate bugs once (a) lands and the silent failures stop hiding them.

Repro environment

  • stx commit (local): 6da28e3193 (fix(parser): advance index after brace match in template-literal scanner — current main)
  • Bun: 1.3.5-canary.12
  • macOS arm64

Happy to PR (a) — one-line change — if that's the preferred direction.

Sign in to comment on this issue.