common.js
This file
Path
src/common.js
59 lines · 2.0 KiB · JavaScript
Last changed by
Fixed #66: Incorrectly trying to modify a frozen objectMichel Weststratebefore adoption0834d8a
History of this fileTake it
Merge pull request #68 from mweststrate/feature/reuseMichel Weststratebefore adoption20394c0
lines 1–33why, one step back1export const PROXY_STATE = Symbol("immer-proxy-state") // TODO: create per closure, to avoid sharing proxies between multiple immer version2export let autoFreeze = true34export function isProxy(value) {5 return !!value && !!value[PROXY_STATE]6}78export function isProxyable(value) {9 if (!value) return false10 if (typeof value !== "object") return false11 if (Array.isArray(value)) return true12 const proto = Object.getPrototypeOf(value)13 return proto === null || proto === Object.prototype14}1516export function freeze(value) {17 if (autoFreeze) {18 Object.freeze(value)19 }20 return value21}2223/**24 * Automatically freezes any state trees generated by immer.25 * This protects against accidental modifications of the state tree outside of an immer function.26 * This comes with a performance impact, so it is recommended to disable this option in production.27 * It is by default enabled.28 *29 * @returns {void}30 */31export function setAutoFreeze(enableAutoFreeze) {32 autoFreeze = enableAutoFreeze33}Fixed #66: Incorrectly trying to modify a frozen objectMichel Weststratebefore adoption0834d8a
lines 34–59why, one step back3435export function finalizeNonProxiedObject(parent, finalizer) {36 // If finalize is called on an object that was not a proxy, it means that it is an object that was not there in the original37 // tree and it could contain proxies at arbitrarily places. Let's find and finalize them as well38 if (!isProxyable(parent)) return39 if (Object.isFrozen(parent)) return40 let modified = false41 if (Array.isArray(parent)) {42 for (let i = 0; i < parent.length; i++) {43 const child = parent[i]44 if (isProxy(child)) {45 parent[i] = finalizer(child)46 modified = true47 } else finalizeNonProxiedObject(child, finalizer)48 }49 } else {50 for (let key in parent) {51 const child = parent[key]52 if (isProxy(child)) {53 parent[key] = finalizer(child)54 modified = true55 } else finalizeNonProxiedObject(child, finalizer)56 }57 }58 if (modified) freeze(parent)59}