I try to use mobx in nodejs but the script is not work.
(async function () {
const mobx = require('./mobx.umd.min.js')
// example 2, array of primitives
// observes computed value, works
const { observable, computed, autorun } = mobx;
var numbers = observable([1, 2, 3]);
autorun(() => {
console.log(numbers);
});
numbers.push(4); //autorun does not trigger
numbers.push(4); //autorun does not trigger
})();
but the script works in broswer:
<!DOCTYPE html>
<html lang="en">
<body>
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mobx/5.15.4/mobx.umd.min.js"></script>
<script type="module">
// example 2, array of primitives
// observes computed value, works
const { observable, computed, autorun } = mobx;
var numbers = observable([1, 2, 3]);
autorun(() => {
window.numbers = numbers;
const app = document.querySelector("#app");
console.log(`numbers`, numbers);
app.innerHTML = "<p>" + numbers.join(", ") + "</p>";
});
numbers.push(4); //autorun does not trigger
</script>
</body>
</html>
I want to use mobx in nodejs, How could I use mobx in nodejs directly?
You are referencing numbers
array inside Node.js autorun
, but you have not changed it, so there is not reason to MobX to autorun
. Observers (e.g. autorun, computed, observer and etc.) only react when something was changed.
You only changed array content, not the array itself. So if your code was something like that:
autorun(() => {
console.log(numbers.map(x => x);
});
It would work as expected, because here you actually referencing array content. And browser version works because you are using numbers.join
and referencing array content with that call.
Next time try to test identical cases in both environments just to be sure that the error in not in your code!