Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/set-array-batch-finally.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"mobx": patch
---

`set(array, index, value)` now ends its batch when an `intercept` handler or an `observe` listener throws. Before, the batch stayed open and no reaction ran again.
17 changes: 17 additions & 0 deletions packages/mobx/__tests__/base/object-api.js
Original file line number Diff line number Diff line change
Expand Up @@ -659,3 +659,20 @@ test("defineProperty notifies keys observers", () => {
expect(obj.hasOwnProperty("foo")).toBe(false)
expect(reactionCount).toBe(2)
})

test("set(array) ends its batch when an interceptor throws", () => {
const arr = observable([1])
const box = observable.box(0)
const seen = []
const disposeAutorun = autorun(() => seen.push(box.get()))
const disposeIntercept = mobx.intercept(arr, () => {
throw new Error("rejected")
})

expect(() => set(arr, 0, 5)).toThrow("rejected")
box.set(1)

expect(seen).toEqual([0, 1])
disposeIntercept()
disposeAutorun()
})
11 changes: 7 additions & 4 deletions packages/mobx/src/api/object-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,14 @@ export function set(obj: any, key: any, value?: any): void {
die(42, key)
}
startBatch()
if (key >= obj.length) {
obj.length = key + 1
try {
if (key >= obj.length) {
obj.length = key + 1
}
obj[key] = value
} finally {
endBatch()
}
obj[key] = value
endBatch()
} else {
die(8)
}
Expand Down