【问题标题】:Error while converting `undefined` to `map<string, AnonymousModel>`将 `undefined` 转换为 `map<string, AnonymousModel>` 时出错
【发布时间】:2017-10-17 07:55:43
【问题描述】:

我正在尝试使用 mobx-state-tree 创建一个超级简单的嵌套存储,但我不知道如何让它工作。要么这个库非常不直观,要么我只是遗漏了一些明显的东西。我尝试将所有内容都包含在 MST.types.optional() 中,看看是否会有所不同,但没有。

这个想法是 Orders 商店有许多买卖订单。我想创建一个没有任何订单的空商店。

当我尝试执行 Orders.js 时,我收到以下错误:

Error: [mobx-state-tree] Error while converting `undefined` to `map<string, AnonymousModel>`: value `undefined` is not assignable to type: `map<string, AnonymousModel>` (Value is not a plain object), expected an instance of `map<string, AnonymousModel>` or a snapshot like `Map<string, { timestamp: Date; amount: number; price: number }>` instead.`

order.js

const MST = require("mobx-state-tree")

const Order = MST.types.model({
    timestamp: MST.types.Date,
    amount: MST.types.number,
    price: MST.types.number,
}).actions(self => {
    function add(timestamp, price, amount) {
        self.timestamp = timestamp
        self.price = price
        self.amount = amount
    }
    return { add }
})

module.exports = Order

orders.js

const MST = require("mobx-state-tree")
const Order = require('./order')

const Orders = MST.types.model({
    buys: MST.types.map(Order),
    sells: MST.types.map(Order),
}).actions(self => {
    function addOrder(type, timestamp, price, amount) {
        if(type === 'buy'){
            self.buys.add(timestamp, price, amount)
        } else if(type === 'sell') {
            self.sells.add(timestamp, price, amount)
        } else throw Error('bad order type') 
    }
    return { addOrder }
})
Orders.create()

【问题讨论】:

    标签: javascript node.js mobx mobx-state-tree


    【解决方案1】:

    是的,您需要将所有内容包装为 types.optional 并为此提供默认快照。 这是一个例子

    const MST = require("mobx-state-tree")
    const Order = require('./order')
    
    const Orders = MST.types.model({
        buys: MST.types.optional(MST.types.map(Order), {}),
        sells: MST.types.optional(MST.types.map(Order), {}),
    }).actions(self => {
        function addOrder(type, timestamp, price, amount) {
            if(type === 'buy'){
                self.buys.add(timestamp, price, amount)
            } else if(type === 'sell') {
                self.sells.add(timestamp, price, amount)
            } else throw Error('bad order type') 
        }
        return { addOrder }
    })
    Orders.create()
    

    types.optional 在幕后所做的是拦截 undefined 并将其替换为您的默认值:)

    【讨论】:

    • 好的,谢谢。记住要这样做有点皮塔饼,但幸运的是模型不会经常更换。
    猜你喜欢
    • 1970-01-01
    • 2021-04-25
    • 2016-07-29
    • 2013-05-24
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    • 2015-11-21
    • 2016-07-21
    相关资源
    最近更新 更多