Skip to content

Commit 9daa5c3

Browse files
committed
fix: writing a signal inside trigger after reading it crashes flush
The trigger() sub collects deps mid-run like an executing effect but was missing RecursedCheck, so a setter call inside fn on an already-read signal made propagate() notify-queue the non-effect sub, and flush() then crashed calling its nonexistent fn. The unbatched write also flushed immediately while the finally block propagated the same dep again, rerunning effects twice per trigger. Add RecursedCheck so writes to already-read deps take the recursed-write path, and wrap the whole trigger in a batch so reads and writes settle as one atomic change set with a single flush. Fixes #122
1 parent ccef250 commit 9daa5c3

2 files changed

Lines changed: 37 additions & 2 deletions

File tree

‎src/index.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -210,12 +210,18 @@ export function effectScope(fn: () => void): () => void {
210210
}
211211

212212
export function trigger(fn: () => void) {
213+
// RecursedCheck marks this sub as mid-run (like an executing effect), so
214+
// writes inside fn to already-read deps take the recursed-write path in
215+
// propagate/shallowPropagate instead of notify-queueing this non-effect
216+
// node, which would crash in run(). Batching defers those writes' flush
217+
// so fn's reads and writes settle as one atomic change set.
213218
const sub: ReactiveNode = {
214219
deps: undefined,
215220
depsTail: undefined,
216-
flags: ReactiveFlags.Watching,
221+
flags: ReactiveFlags.Watching | ReactiveFlags.RecursedCheck,
217222
};
218223
const prevSub = setActiveSub(sub);
224+
++batchDepth;
219225
try {
220226
fn();
221227
} finally {
@@ -231,7 +237,7 @@ export function trigger(fn: () => void) {
231237
shallowPropagate(subs);
232238
}
233239
}
234-
if (!batchDepth) {
240+
if (!--batchDepth) {
235241
flush();
236242
}
237243
}

‎tests/trigger.spec.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,32 @@ test('should not notify the trigger function sub', () => {
6262
src2();
6363
});
6464
});
65+
66+
test('should allow writing a signal after reading it', () => {
67+
const src1 = signal(1);
68+
69+
trigger(() => {
70+
src1();
71+
src1(src1() + 1);
72+
});
73+
expect(src1()).toBe(2);
74+
});
75+
76+
test('should rerun effect once when writing a signal after reading it', () => {
77+
const src1 = signal(1);
78+
79+
let triggers = 0;
80+
81+
effect(() => {
82+
triggers++;
83+
src1();
84+
});
85+
86+
expect(triggers).toBe(1);
87+
trigger(() => {
88+
src1();
89+
src1(src1() + 1);
90+
});
91+
expect(triggers).toBe(2);
92+
expect(src1()).toBe(2);
93+
});

0 commit comments

Comments
 (0)