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

Mobx4中observable.map的keys()/values()返回迭代器而非数组问题求助

Why observable.map.keys() Returns an Iterator Instead of an Array (and How to Fix It)

Hey there! Let's unpack the issue you're facing with your MobX UiStore.

First off, the behavior you're seeing isn't a bug with MobX or your decorate syntax—it's actually how native ES6 Maps work. MobX's observable.map is just a reactive wrapper around the standard ES6 Map, so it inherits all of the native Map's methods. And guess what? The native Map.keys() method doesn't return an array directly—it gives you a MapIterator object (that {next: ƒ, Symbol(Symbol.iterator): ƒ} thing you're seeing).

Quick side note: Your code has a tiny redundancy. You already initialized loaders as observable.map({}), which makes it reactive out of the box. The decorate line marking loaders: observable is unnecessary here—you can safely remove that without breaking anything.

Fixes to Get an Array of Keys

Converting that iterator to an array is super straightforward. Here are two common ways to do it:

1. Use Array.from()

Wrap the iterator in Array.from() to turn it into a proper array:

const loaderKeys = Array.from(uiStore.loaders.keys());

2. Use the Spread Operator (...)

The ES6 spread operator can also consume iterators and turn them into arrays:

const loaderKeys = [...uiStore.loaders.keys()];

Bonus: Add a Helper Method to Your Store

If you want to avoid repeating this conversion everywhere, you can add a small helper method to your UiStore:

class UiStore {
  loaders = observable.map({});

  // Helper to get keys as an array
  getLoaderKeys() {
    return Array.from(this.loaders.keys());
  }
}

// No need to mark loaders as observable here anymore
export default decorate(UiStore, {});

Now you can just call uiStore.getLoaderKeys() whenever you need the array of keys!

内容的提问来源于stack exchange,提问作者Miha Šušteršič

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:59:34