Mobx 4.2.0中computed计算属性不生效问题咨询
Hey there, let's break down why your velocity computed property only logs 'entry' once.
The Core Issue: MobX Computeds Are Lazy & Reactive
MobX's computed properties follow two key rules:
- They only recalculate when their observable dependencies change (your
speedvariable here). - Crucially, they only recalculate if the computed value is actually being accessed or observed somewhere in your code.
Looking at your code: you're updating speed every 3 seconds with model.change(), but nowhere in the provided snippet do you ever read model.velocity. MobX is optimized to avoid unnecessary work—if no part of your code uses the computed value, it has no reason to recalculate it after the initial (one-time) evaluation.
How to Fix It
You have two straightforward ways to get the computed property to update with speed:
Fix 1: Explicitly Access the Computed Property
If you want to see the recalculation in your console, just access model.velocity whenever you update speed:
setInterval(() => { model.change({ speed: ++total }) // Access the computed value to trigger recalculation console.log('Updated velocity:', model.velocity) }, 3000)
Fix 2: Use the Computed Property in an Observed Component (React Use Case)
If you're using this model in a React app, wrap your component with the @observer decorator from mobx-react and render the velocity value. MobX will automatically track the dependency and recalculate velocity whenever speed changes:
import { observer } from 'mobx-react' @observer class VelocityDisplay extends React.Component { render() { return <div>Current Velocity: {this.props.model.velocity}</div> } } // Use the component like this: // <VelocityDisplay model={model} />
Bonus: Forcing Recalculation Without Observation
If you absolutely need the computed value to update even when unused (not recommended for most cases, as it wastes resources), you can use the keepAlive option in MobX 4:
@computed({ keepAlive: true }) get velocity() { console.log('entry') return this.speed*60*60/1000 }
内容的提问来源于stack exchange,提问作者frank wu

