diff --git a/src/api/tojs.ts b/src/api/tojs.ts index 428bedda3..8c13a38de 100644 --- a/src/api/tojs.ts +++ b/src/api/tojs.ts @@ -27,6 +27,9 @@ function toJSHelper(source, options: ToJSOptions, __alreadySeen: Map) if (!options.recurseEverything && !isObservable(source)) return source if (typeof source !== "object") return source + + // Directly return null if source is null + if (source === null) return null // Directly return the Date object itself if contained in the observable if (source instanceof Date) return source @@ -34,9 +37,7 @@ function toJSHelper(source, options: ToJSOptions, __alreadySeen: Map) if (isObservableValue(source)) return toJSHelper(source.get(), options!, __alreadySeen) // make sure we track the keys of the object - if (isObservable(source)) { - keys(source) - } + if (isObservable(source)) keys(source) const detectCycles = options.detectCycles === true diff --git a/test/base/tojs.js b/test/base/tojs.js index b6b8d3c25..9f324a525 100644 --- a/test/base/tojs.js +++ b/test/base/tojs.js @@ -403,4 +403,9 @@ describe("recurseEverything set to true", function() { const convertedObj = mobx.toJS({ key: cycledObj }, { recurseEverything: true }) expect(convertedObj.key).toBe(convertedObj.key.cycle) }) + + test("should return null if source is null", function() { + expect(mobx.toJS(null)).toBeNull() + expect(mobx.toJS(null, { recurseEverything: true })).toBeNull() + }) })