如何在 Mobx-State-Tree 中拥有可为空的字符串值

How to have a nullable string value in Mobx-State-Tree

我正在尝试创建一个具有可选的可为空字符串值的模型。 我试过同时使用

  hint: types.optional(types.string, ""),

  hint: types.maybe(types.string),

当我尝试将 json 对象设置为对象时,两者都会导致错误。 如果我手动循环遍历 json 对象并将空内容设置为空字符串“”,则可以工作。

Error while converting "jsoncontent" at path "content" value null is not assignable to type: string (Value is not a string).

您可以使用 types.maybeNull 得到一个类型,也可以是 null

hint: types.maybeNull(types.string)

您可以使用以下解决方案之一在 Mobx-State-Tree 中拥有可为空的字符串值:

types.maybeNull(types.string) // value can be null

types.optional(types.string, '') // should create empty string if value is not defined