如果你也用了moment,并且在model里将需要修改的数据的类型设置为Date的话,那么我们遇到的可能是同一个问题。直接上代码:
import DS from 'ember-data';
const {Model} = DS;
export default Model.extend({
location: DS.attr('string'),
createdAt: DS.attr('date'),
sightedAt: DS.attr('date'),
cryptid: DS.belongsTo('cryptid'),
witnesses: DS.hasMany('witness')
});
要求是根据输入,调用moment格式化sightedAt为ISO格式。错误的写法是这样:
this.store.findRecord('sighting', id)
.then((sight) => {
sight.set('sightedAt', window.moment(this.sightingDate).format());
});
虽然从语义上来看并没有什么问题,但有一个地方不知道你注意到没有,就是类型。moment.format返回的结果是一个字符串,而我们要求的结果是一个Date类型的对象。
ember在这里的操作就很神秘,既不会自动包装,也不会报错或者警告,而是直接抛弃结果,变成null;这一切都是在后台进行的,也跟踪不到,真的巨坑。正确的写法应该是这样:
this.store.findRecord('sighting', id)
.then((sight) => {
sight.set('sightedAt', new Date(window.moment(this.sightingDate).format()));
});
……只能说自己小心吧。