Helper functions for working with observable state, converting to plain values, and checking observable types. These utilities provide essential functionality for introspection, debugging, and data conversion.
Converts observable data structures to plain JavaScript values, recursively converting all nested observables.
/**
* Converts observable to plain JavaScript value
* @param value - Observable value to convert
* @param options - Conversion options
* @returns Plain JavaScript equivalent
*/
function toJS<T>(value: T, options?: {
/** Whether to convert deeply nested structures */
recurseEverything?: boolean;
/** Whether to export non-enumerable properties */
exportMapsAsObjects?: boolean;
}): T;Usage Examples:
import { observable, toJS } from "mobx";
// Observable object
const person = observable({
name: "Alice",
hobbies: ["reading", "coding"],
address: { city: "New York", zip: "10001" }
});
const plainPerson = toJS(person);
console.log(plainPerson); // Plain object, not observable
// Observable array
const todos = observable([
{ text: "Learn MobX", completed: false },
{ text: "Build app", completed: true }
]);
const plainTodos = toJS(todos);
console.log(Array.isArray(plainTodos)); // true
console.log(plainTodos[0].text); // "Learn MobX"
// Observable Map
const userMap = observable.map([
["user1", { name: "Alice", age: 25 }],
["user2", { name: "Bob", age: 30 }]
]);
const plainMap = toJS(userMap); // Converts to plain object
console.log(plainMap.user1.name); // "Alice"
// Convert Map to actual Map
const plainMapAsMap = toJS(userMap, { exportMapsAsObjects: false });
console.log(plainMapAsMap instanceof Map); // trueFunctions for working with observable objects, arrays, Maps, and Sets in a uniform way.
Returns observable keys of an object, Map, or array indices.
/**
* Returns observable keys of an object, map, or array
* @param obj - Observable object, map, or array
* @returns Array of keys/indices
*/
function keys(obj: any): string[];Returns observable values of an object, Map, or array.
/**
* Returns observable values of an object, map, or array
* @param obj - Observable object, map, or array
* @returns Array of values
*/
function values<T>(obj: T): any[];Returns observable entries (key-value pairs) of an object, Map, or array.
/**
* Returns observable entries of an object, map, or array
* @param obj - Observable object, map, or array
* @returns Array of [key, value] pairs
*/
function entries<T>(obj: T): [string, any][];Usage Examples:
import { observable, keys, values, entries, autorun } from "mobx";
const person = observable({
name: "Alice",
age: 25,
city: "New York"
});
// Reactive access to keys, values, entries
autorun(() => {
console.log("Keys:", keys(person)); // ["name", "age", "city"]
console.log("Values:", values(person)); // ["Alice", 25, "New York"]
console.log("Entries:", entries(person)); // [["name", "Alice"], ...]
});
// Works with Maps
const userMap = observable.map([
["user1", "Alice"],
["user2", "Bob"]
]);
console.log(keys(userMap)); // ["user1", "user2"]
console.log(values(userMap)); // ["Alice", "Bob"]
console.log(entries(userMap)); // [["user1", "Alice"], ["user2", "Bob"]]
// Works with arrays
const items = observable(["a", "b", "c"]);
console.log(keys(items)); // ["0", "1", "2"]
console.log(values(items)); // ["a", "b", "c"]Sets a property value on an observable object, Map, or array.
/**
* Sets property value on observable object, map, or array
* @param obj - Target object, map, or array
* @param key - Property key or array index
* @param value - Value to set
*/
function set<T>(obj: T, key: PropertyKey, value: any): void;
/**
* Sets multiple properties from an object
* @param obj - Target object
* @param values - Object with properties to set
*/
function set<T>(obj: T, values: { [key: string]: any }): void;Removes a property from an observable object, Map, or array.
/**
* Removes property from observable object, map, or array
* @param obj - Target object, map, or array
* @param key - Property key or array index to remove
* @returns True if property was removed
*/
function remove<T>(obj: T, key: PropertyKey): boolean;Checks if an observable object, Map, or array has a specific property.
/**
* Checks if observable object, map, or array has property
* @param obj - Target object, map, or array
* @param key - Property key or array index to check
* @returns True if property exists
*/
function has<T>(obj: T, key: PropertyKey): boolean;Gets a property value from an observable object, Map, or array.
/**
* Gets property value from observable object, map, or array
* @param obj - Target object, map, or array
* @param key - Property key or array index
* @returns Property value
*/
function get<T>(obj: T, key: PropertyKey): any;Usage Examples:
import { observable, set, remove, has, get, autorun } from "mobx";
const person = observable({
name: "Alice"
});
// Set properties
set(person, "age", 25);
set(person, { city: "New York", country: "USA" });
console.log(person.age); // 25
console.log(person.city); // "New York"
// Check and get properties
console.log(has(person, "age")); // true
console.log(has(person, "height")); // false
console.log(get(person, "name")); // "Alice"
// Remove properties
remove(person, "country");
console.log(has(person, "country")); // false
// Works with Maps
const userMap = observable.map();
set(userMap, "user1", { name: "Alice" });
console.log(get(userMap, "user1")); // { name: "Alice" }
// Works with arrays
const items = observable([]);
set(items, 0, "first");
set(items, "length", 3); // Sets array length
console.log(get(items, 0)); // "first"Defines a property on an observable object with the given descriptor.
/**
* Defines property on observable object
* @param obj - Target observable object
* @param key - Property key to define
* @param descriptor - Property descriptor
* @returns True if property was defined
*/
function defineProperty(obj: object, key: PropertyKey, descriptor: PropertyDescriptor): boolean;Gets all own property keys of an observable object.
/**
* Gets all own property keys of observable object
* @param obj - Target observable object
* @returns Array of property keys
*/
function ownKeys(obj: object): PropertyKey[];Usage Examples:
import { observable, defineProperty, ownKeys } from "mobx";
const person = observable({ name: "Alice" });
// Define new property with custom descriptor
defineProperty(person, "age", {
value: 25,
writable: true,
enumerable: true,
configurable: true
});
// Get all property keys
console.log(ownKeys(person)); // ["name", "age"]
// Define computed-like property
defineProperty(person, "info", {
get() {
return `${this.name} (${this.age})`;
},
enumerable: true,
configurable: true
});
console.log(person.info); // "Alice (25)"Functions for determining the type and status of MobX observables.
/**
* Checks if value is observable
* @param value - Value to check
* @returns True if value is observable
*/
function isObservable(value: any): boolean;
/**
* Checks if object property is observable
* @param obj - Object to check
* @param key - Property key
* @returns True if property is observable
*/
function isObservableProp(obj: any, key: PropertyKey): boolean;
/**
* Checks if value is observable array
* @param value - Value to check
* @returns True if value is observable array
*/
function isObservableArray(value: any): value is IObservableArray<any>;
/**
* Checks if value is observable object
* @param value - Value to check
* @returns True if value is observable object
*/
function isObservableObject(value: any): boolean;
/**
* Checks if value is observable Map
* @param value - Value to check
* @returns True if value is observable Map
*/
function isObservableMap(value: any): value is ObservableMap<any, any>;
/**
* Checks if value is observable Set
* @param value - Value to check
* @returns True if value is observable Set
*/
function isObservableSet(value: any): value is ObservableSet<any>;
/**
* Checks if value is boxed observable value
* @param value - Value to check
* @returns True if value is boxed observable
*/
function isBoxedObservable(value: any): value is IObservableValue<any>;/**
* Checks if value is computed value
* @param value - Value to check
* @returns True if value is computed
*/
function isComputed(value: any): boolean;
/**
* Checks if object property is computed
* @param obj - Object to check
* @param key - Property key
* @returns True if property is computed
*/
function isComputedProp(obj: any, key: PropertyKey): boolean;/**
* Checks if function is action
* @param fn - Function to check
* @returns True if function is action
*/
function isAction(fn: any): boolean;
/**
* Checks if function is flow
* @param fn - Function to check
* @returns True if function is flow
*/
function isFlow(fn: any): boolean;Usage Examples:
import {
observable,
computed,
action,
flow,
isObservable,
isObservableArray,
isObservableMap,
isComputed,
isAction,
isFlow
} from "mobx";
const obj = observable({ name: "Alice" });
const arr = observable([1, 2, 3]);
const map = observable.map([["key", "value"]]);
const comp = computed(() => obj.name.toUpperCase());
const act = action(() => {});
const flw = flow(function* () {});
console.log(isObservable(obj)); // true
console.log(isObservable("string")); // false
console.log(isObservableArray(arr)); // true
console.log(isObservableArray(obj)); // false
console.log(isObservableMap(map)); // true
console.log(isComputed(comp)); // true
console.log(isAction(act)); // true
console.log(isFlow(flw)); // true
// Check properties
console.log(isObservableProp(obj, "name")); // true
console.log(isComputedProp({ get foo() { return "bar"; } }, "foo")); // falseFunctions for inspecting the internal state and dependencies of observables.
Gets the underlying atom of an observable.
/**
* Gets the underlying atom of an observable
* @param thing - Observable to get atom from
* @param property - Optional property name for object properties
* @returns The atom instance
*/
function getAtom(thing: any, property?: PropertyKey): IAtom;Gets debug name of an observable for debugging purposes.
/**
* Gets debug name of observable
* @param thing - Observable to get name from
* @param property - Optional property name
* @returns Debug name string
*/
function getDebugName(thing: any, property?: PropertyKey): string;Usage Examples:
import { observable, getAtom, getDebugName } from "mobx";
const person = observable({
name: "Alice",
age: 25
}, {}, { name: "Person" });
console.log(getDebugName(person)); // "Person"
console.log(getDebugName(person, "name")); // "Person.name"
const atom = getAtom(person, "name");
console.log(atom.name); // "Person.name"Runs code without establishing observable dependencies.
/**
* Runs function without tracking observable dependencies
* @param fn - Function to run untracked
* @returns Result of the function
*/
function untracked<T>(fn: () => T): T;Usage Examples:
import { observable, computed, untracked, autorun } from "mobx";
const state = observable({
count: 0,
lastAccessed: 0
});
// Computed that doesn't track lastAccessed
const doubleCount = computed(() => {
// This access won't create dependency
untracked(() => {
state.lastAccessed = Date.now();
});
return state.count * 2; // Only depends on count
});
autorun(() => {
console.log("Double count:", doubleCount.get());
});
state.lastAccessed = Date.now(); // Won't trigger reaction
state.count = 5; // Will trigger reactionRegisters a callback that executes when an observable becomes observed by a reaction.
/**
* Registers callback for when observable becomes observed
* @param observable - Observable to monitor
* @param listener - Callback to execute
* @returns Disposer function
*/
function onBecomeObserved(
observable: IObservable | IComputedValue<any> | IObservableArray<any> | ObservableMap<any, any> | ObservableSet<any> | IObservableValue<any>,
listener: () => void
): () => void;
/**
* Registers callback for when object property becomes observed
* @param object - Object containing the property
* @param property - Property key to monitor
* @param listener - Callback to execute
* @returns Disposer function
*/
function onBecomeObserved<K>(
object: object,
property: K,
listener: () => void
): () => void;Registers a callback that executes when an observable is no longer observed by any reactions.
/**
* Registers callback for when observable becomes unobserved
* @param observable - Observable to monitor
* @param listener - Callback to execute
* @returns Disposer function
*/
function onBecomeUnobserved(
observable: IObservable | IComputedValue<any> | IObservableArray<any> | ObservableMap<any, any> | ObservableSet<any> | IObservableValue<any>,
listener: () => void
): () => void;
/**
* Registers callback for when object property becomes unobserved
* @param object - Object containing the property
* @param property - Property key to monitor
* @param listener - Callback to execute
* @returns Disposer function
*/
function onBecomeUnobserved<K>(
object: object,
property: K,
listener: () => void
): () => void;Usage Examples:
import { observable, onBecomeObserved, onBecomeUnobserved, autorun } from "mobx";
const data = observable({ count: 0, name: "Test" });
// Monitor when entire object becomes observed/unobserved
const observedDisposer = onBecomeObserved(data, () => {
console.log("Data object is now being observed");
});
const unobservedDisposer = onBecomeUnobserved(data, () => {
console.log("Data object is no longer being observed");
});
// Monitor specific property
const propObservedDisposer = onBecomeObserved(data, "count", () => {
console.log("Count property is now being observed");
});
// Start observing - this will trigger onBecomeObserved callbacks
const reactionDisposer = autorun(() => {
console.log(`Count: ${data.count}`);
});
// Stop observing - this will trigger onBecomeUnobserved callbacks
reactionDisposer();
// Clean up listeners
observedDisposer();
unobservedDisposer();
propObservedDisposer();Type definition for parameterless functions.
/**
* Type for parameterless functions
*/
type Lambda = () => void;Symbol used internally to mark MobX objects.
/**
* Symbol used to mark MobX objects
*/
declare const $mobx: unique symbol;Usage Examples:
import { observable, $mobx } from "mobx";
const obj = observable({ name: "Alice" });
console.log($mobx in obj); // true
console.log(obj[$mobx]); // Internal MobX administration objectinterface IAtom {
name: string;
reportObserved(): boolean;
reportChanged(): void;
}
interface IEqualsComparer<T> {
(a: T, b: T): boolean;
}
interface IEnhancer<T> {
(value: T, name?: string): T;
}
interface IInterceptable<T> {
intercept(handler: IInterceptor<T>): Lambda;
}
interface IListenable {
observe(handler: (change: any) => void): Lambda;
}
type IInterceptor<T> = (change: T) => T | null;