gpt4 book ai didi

javascript - `cannot read property ‘setDirtyAttribute’ 为 null ` even if you use ` YourModel.create({…}) ` in ` ember-typescript-cli`

转载 作者:行者123 更新时间:2023-12-02 23:16:07 25 4
gpt4 key购买 nike

面对cannot read property 'setDirtyAttribute' of null即使您使用 YourModel.create({...})ember-typescript-cli创建一个 EmberObject。

型号:

import DS from 'ember-data';
import {computed} from "@ember/object";

export default class Person extends DS.Model {
@DS.attr() firstName!: string;
@DS.attr() lastName!: string;
@DS.attr() age!: number;
@DS.attr() desc?: string;


@computed("firstName", "lastName")
public get fullName() {
return `${this.firstName} ${this.lastName}`;
}
}

路线:

export default class Persons extends Route {
@service() public store!: DS.Store;

constructor() {
super(...arguments);

const persons: Person[] = [
Person.create({firstName: "first1", lastName: "last1", age: 10}),
Person.create({firstName: "first2", lastName: "last2", age: 320}),
Person.create({firstName: "first3", lastName: "last3", age: 30}),
];
persons.forEach(p => this.store.createRecord('person', p));
}
}

进入页面时报错:

Uncaught TypeError: Cannot read property 'setDirtyAttribute' of null
at Person.set (-private.js:144)
at ComputedProperty._set (metal.js:3543)
at ComputedProperty.setWithSuspend (metal.js:3532)
at ComputedProperty.set (metal.js:3503)
at initialize (core_object.js:67)
at Function.create (core_object.js:692)
at new Persons (persons.js:23)
at Function.create (core_object.js:684)
at FactoryManager.create (container.js:549)
at instantiateFactory (container.js:359)

所以我必须使用像 this.store.createRecord('person', {firstName: "first1", lastName: "last1", age: 10}) 这样的东西而不是this.store.createRecord('person', <a Person class instance>) ,这根本不是 typescript 式的。所以我希望找到一种更优雅的方式将ember特性结合到typescript中,而不是使用any或裸露object无处不在。

有什么建议吗?

最佳答案

Ember Data 的文档非常清楚地表明您不应该使用 Model.create({})。它不仅是私有(private) API,甚至还记录了模型实例只能使用商店服务创建:

Create should only ever be called by the store. To create an instance of a Model in a dirty state use store.createRecord.

To create instances of Model in a clean state, use store.push

https://api.emberjs.com/ember-data/3.11/classes/Model/methods/create?anchor=create&show=inherited%2Cprotected%2Cprivate

默认情况下,Ember Data 的公共(public) API 应能与 Typescript 良好配合。 known and documented bug ember-data@3.11.0 中的内容应该已在以后的版本中修复。

请引用Ember CLI TypeScript's documentation about Ember Data support了解受支持的设置。

关于javascript - `cannot read property ‘setDirtyAttribute’ 为 null ` even if you use ` YourModel.create({…}) ` in ` ember-typescript-cli`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57156048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com