snapshot <function> is not assignable to type: frozen
#2271
-
Hi. I try to create a simple mst store which I don't need to serialize, just use as a storage for things: import { types } from 'mobx-state-tree'
import { NavigateFunction, Location } from 'react-router'
/**
* This is a wrapper store for keeping current react router things
*/
const routerStore$ = types
.model('RouterStore', {
location: types.frozen<Location>(),
navigate: types.frozen<NavigateFunction>(),
})
.actions((self) => ({
setLocation: (location: Location) => {
self.location = location
},
setNavigate: (navigate: NavigateFunction) => {
self.navigate = navigate // ERROR: snapshot <function> is not assignable to type: `frozen`
},
}))
export const routerStore = routerStore$.create() I know I can use just a regular mobx store, but for uniformity I made it an MST model. Is there still a way to keep functions in MST stores? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Yep! If you don't need serialization, you can get most of the benefits by using volatile state. It is less restrictive, but won't participate in snapshots, patches, and so on. |
Beta Was this translation helpful? Give feedback.
-
Yes, this should actually work, you just need to do import { types } from "mobx-state-tree";
const someFunction1 = () => {
console.log("Hello, world");
};
const someFunction2 = () => {
console.log("Goodbye, world");
};
const functionWithParam = (a: string) => {
console.log(a);
};
export const SomeModel = types
.model({
name: types.string,
func: types.frozen<typeof someFunction1>(someFunction1),
funcWithParam: types.frozen<typeof functionWithParam>(functionWithParam),
})
.volatile(() => ({
callback: someFunction2,
callbackWithParam: functionWithParam,
}));
const instance = SomeModel.create({ name: "Example" });
instance.func;
// Does not work:
// instance.funcWithParam("a");
instance.callback();
instance.callbackWithParam("a"); Personally, I might use volatile state instead. That way you can just store the function as a function and get access to its parameters correctly. |
Beta Was this translation helpful? Give feedback.
Yes, this should actually work, you just need to do
types.frozen<typeof Location>()
instead. Although I wouldn't actually recommend doing it this way because you won't have access to any parameters you need. See: