Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

(メモ) mobx-state-treeでやりがちな循環依存

More than 1 year has passed since last update.

(注意:糞記事です)

mobs-state-treeは便利なのですが、よく循環依存を作りがちです。

こういうのでコンパイルが死んでいませんか?

import { types, getParentOfType } from "mobx-state-tree";

const Parent = types.model("Parent", {
    child: types.late(() => Child)
}).actions(self => {
    return {}
})

const Child = types.model("Child", {}).views(self => {
    return {
        get parent() {
            // 下記の評価結果は any になり、そしてエラーに!
            return getParentOfType(self, Parent)
        }
    }
})

でも下記はOKだったりします

const Parent = types.model("Parent", {}).views(self => {
    return {
        get child() {
            return Child.create({})
        }
    }
})

const Child = types.model("Child", {}).views(self => {
    return {
        get parent() {
            return getParentOfType(self, Parent)
        }
    }
})

これもOK

import { types, getParentOfType } from "mobx-state-tree";

const Parent = types.model("Parent", {
    child: types.late(() => Child)
})

const Child = types.model("Child", {})
.actions(self => {
    const parent =  () => getParentOfType(self, Parent)
    return {
        doSomething() {
            parent().child
        }
    }
})
knjname
Zenn: https://zenn.dev/knjname
http://knjname.hateblo.jp/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away