Skip to content

Commit

Permalink
Fix #2871 toJS throws with configure({ useProxies: "ifavailable" }) (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
urugator committed Apr 3, 2021
1 parent a68a14f commit 6b324ed
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/fluffy-coats-fry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"mobx": patch
---

Fix [#2871](https://github.com/mobxjs/mobx/issues/2871): `toJS` throws with `configure({ useProxies: "ifavailable" })`
13 changes: 12 additions & 1 deletion packages/mobx/__tests__/v5/base/tojs.js
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ test("#285 non-mobx class instances with toJS", () => {
})

test("verify #566 solution", () => {
function MyClass() {}
function MyClass() { }
const a = new MyClass()
const b = mobx.observable({ x: 3 })
const c = mobx.observable({ a: a, b: b })
Expand Down Expand Up @@ -367,3 +367,14 @@ describe("recurseEverything set to true", function () {
)
})
})

test("Does not throw on object with configure({ useProxies: 'ifavailable'}) #2871", () => {
const { useProxies } = mobx._resetGlobalState;
mobx.configure({ useProxies: "ifavailable" })
expect(() => {
const o = mobx.observable({ key: "value" });
const dispose = mobx.autorun(() => mobx.toJS(o))
dispose();
}).not.toThrow();
mobx.configure({ useProxies })
})
14 changes: 8 additions & 6 deletions packages/mobx/src/api/tojs.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import {
keys,
isObservable,
isObservableArray,
isObservableValue,
isObservableMap,
isObservableSet,
getPlainObjectKeys,
die
die,
IIsObservableObject,
$mobx,
objectPrototype
} from "../internal"

function cache<K, V>(map: Map<any, any>, key: K, value: V): V {
Expand Down Expand Up @@ -49,10 +50,11 @@ function toJSHelper(source, __alreadySeen: Map<any, any>) {
return res
} else {
// must be observable object
keys(source) // make sure keys are observed
const res = cache(__alreadySeen, source, {})
getPlainObjectKeys(source).forEach((key: any) => {
res[key] = toJSHelper(source[key], __alreadySeen)
;((source as any) as IIsObservableObject)[$mobx].ownKeys_().forEach((key: any) => {
if (objectPrototype.propertyIsEnumerable.call(source, key)) {
res[key] = toJSHelper(source[key], __alreadySeen)
}
})
return res
}
Expand Down

0 comments on commit 6b324ed

Please sign in to comment.