You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mobx 4.2.0中computed计算属性不生效问题咨询

Why does my MobX 4.2.0 computed property only run once?

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 speed variable 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:56:39