You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Promise内设置Knockout Observable不生效问题排查

问题分析与修复方案

你的代码里有两个核心错误导致Observable无法正确更新:

  1. 错误修改recCount的值
    你现在用self.recCount = ko.observable(9);重新赋值了一个新的Observable对象,这会断开原来页面绑定的那个Observable引用,页面自然不会更新。正确的做法是调用已创建的Observable函数,传入新值:
self.recCount(9);
  1. 错误更新myRecords数组
  • 你试图推入的recSet是空数组,根本没有数据;
  • 即使recSet有数据,push(recSet)会把整个数组作为单个元素加入ObservableArray,而不是逐个添加记录。

如果要直接替换整个记录数组,用:

self.myRecords(records);

如果要追加新记录到现有数组,用展开运算符把记录逐个推入:

self.myRecords.push(...records);

修正后的完整代码

function TILViewModel()
{
   var self = this;
   console.log("get default container");
   var container = CloudKit.getDefaultContainer();

   var publicDB = container.privateCloudDatabase;

   self.myRecords = ko.observableArray();
   self.recCount = ko.observable(3);
   // Fetch public records
   self.fetchRecords = function()
   {
       console.log("fetching records from " + publicDB);
       var query = { recordType: 'examRecord', sortBy: [{ fieldName: 'studyDate'}] };
 
       // Execute the query.
       return publicDB.performQuery(query).then(function(response)
       {
           if(response.hasErrors)
           {
              console.error(response.errors[0]);
              return;
           }
          var records = response.records;
          var numberOfRecords = records.length;
          if (numberOfRecords === 0)
          {
               console.error('No matching items');
               return;
          }
    
          console.log(records.length + " records")
          // 直接替换整个记录数组
          self.myRecords(records);
          // 更新计数为实际查询到的记录数
          self.recCount(numberOfRecords);
       });
   };
}

内容的提问来源于stack exchange,提问作者john elemans

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 21:05:22