Unexpected "Detected store mutation during atom read" message triggered #3208
Replies: 4 comments 3 replies
-
|
Just went through my debug output again and I think these two places cause this. They actually violate the rule by calling set in the getter: jotai/src/vanilla/utils/unwrap.ts Lines 51 to 56 in 83dce49 jotai/src/vanilla/utils/unwrap.ts Lines 77 to 86 in 83dce49 |
Beta Was this translation helpful? Give feedback.
-
|
#3179 (comment) |
Beta Was this translation helpful? Give feedback.
-
|
I found an even easier reproducer: const example = atom('Hello')
const store = createStore()
store.get(example)
const unwrapAtom = unwrap(example)
store.get(unwrapAtom)So this seems to happen if the atom that is unwrapped was already read before and has an existing value. I instrumented the code with log messages and got the following result. Seems like there are multiple in-flight reads happening in parallel while one of them is writing eventually and letting the reads up in the stack fail: |
Beta Was this translation helpful? Give feedback.
-
Analysis & WorkaroundThis happens because The Flow:
Workaround 1: Separate the unwrap// Create unwrapped atom outside the effect
const unwrappedDocRef = unwrap(documentRefAtom);
const atomEffect1 = withAtomEffect(valueAtom, (get) => {
get(unwrappedDocRef); // Read pre-unwrapped atom
});Workaround 2: Use loadable with checkimport { loadable } from "jotai/utils";
const loadableDocRef = loadable(documentRefAtom);
const atomEffect1 = withAtomEffect(valueAtom, (get) => {
const result = get(loadableDocRef);
if (result.state === "hasData") {
// Use result.data
}
});Workaround 3: Defer with setTimeoutconst atomEffect1 = withAtomEffect(valueAtom, (get, set) => {
setTimeout(() => {
get(unwrap(documentRefAtom));
}, 0);
});Root CauseThis seems like a timing issue between Workaround 1 should be the cleanest fix for your case. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Bug Description
We have some trouble with the latest jotai updates (wanted to upgrade jotai 2.15.1->2.16.1 and jotai-effect 2.1.3->2.2.3) that include #3179. This warning is triggered in our code although I can't see an obvious reason for that.
I was able to generate this minimal example (also linked as a codesandbox):
It seems to have been connected to:
unwrapin an effect added viawithAtomEffect.Once I remove either of the two
get(...)lines or the unwrap, the error disappears. This also happens when I replaceunwrapwithloadable.I'm not sure if this is an issue of
jotaiorjotai-effectso I decided to open a thread here. I hope anyone here has a clue on why this happens and how this can be resolved.Reproduction Link
https://codesandbox.io/p/sandbox/h5vw53?file=%2Fsrc%2Fjotai-example.tsx
Beta Was this translation helpful? Give feedback.
All reactions