错误"试图在不允许突变的数据库上进行突变操作."在indexedDB中检索数据时

Error "A mutation operation was attempted on a database that did not allow mutations." when retrieving data in indexedDB

本文关键字:突变 quot indexedDB 操作 数据 检索 不允许 错误 数据库      更新时间:2023-09-26

我有这个简单的示例代码:

var request = mozIndexedDB.open('MyTestDatabase');
request.onsuccess = function(event){
  var db = event.target.result;
  var request = db.setVersion('1.0');
  request.onsuccess = function(event){
    console.log("Success version.");
    if(!db.objectStoreNames.contains('customers')){
      console.log("Creating objectStore");
      db.createObjectStore('customers', {keyPath: 'ssn'});
    }
    var transaction = db.transaction([],  IDBTransaction.READ_WRITE, 2000);
    transaction.oncomplete = function(){
      console.log("Success transaction");
      var objectStore = transaction.objectStore('customers');
    };
  };
};

我得到这个:

试图在不允许修改的数据库上执行修改操作。" code: "6

var objectStore = transaction.objectStore('customers');

想不出来-我做错了什么?

只能在版本变更事务中创建或删除对象存储

见:https://developer.mozilla.org/en-US/docs/IndexedDB/IDBDatabase

我想我找到答案了。我不应该在oncomplete中访问objectStore。我只需要在做了新的交易后再做。正确的方法是:

var transaction = db.transaction([],  IDBTransaction.READ_WRITE, 2000);
    transaction.oncomplete = function(){
      console.log("Success transaction");
    };
var objectStore = transaction.objectStore('customers');

顺便说一句,这就是Mozilla的MDN所显示的。https://developer.mozilla.org/en/IndexedDB/Using_IndexedDB section_10

我没有尝试该代码,但根据文档判断,您不应该将空列表作为第一个参数传递给db.transaction() -它应该是db.transaction(["customers"], ...),因为您想使用该对象存储