IndexedDB 未捕获的无效状态错误:无法在'IDBDatabase'上执行'transaction':版本更改事务正在运行

ohtdti5x  于 2022-12-09  发布在  IndexedDB
关注(0)|答案(4)|浏览(443)

我必须承认我对indexedDB还很陌生
我写了一个简单的代码indexedDB,如下所示:

function go() {
   var req = window.indexedDB.open("Uploader", 1),
      db;
   req.onerror = function (e) {
      console.log("Error");
   };
   req.onsuccess = function (e) {
      db = e.target.result;
   };
   req.onupgradeneeded = function (e) {
      console.log(db);
      db = e.target.result;
      var os = db.createObjectStore("Files", { keyPath: "files" });
      os.createIndex("text", "text_file", { unique: false });
      var trans = db.transaction(["text"], "readwrite");
      var objectstore = trans.objectStore("text");
      var addreq = objectstore.add("Instructions.js");
      addreq.onsuccess = function (e) {
         console.log("Success!");
         console.dir(e);
      };
   };
}

它给我的错误是Uncaught InvalidStateError: Failed to execute 'transaction' on 'IDBDatabase': A version change transaction is running.
这是说A version change Transaction is running,但据我所知,版本更改事务是从IDBFactory.open方法进行的,我没有使用,我已经指定此事务是readwrite,此事务在onupgradeneeded中,那么为什么会出现错误?
我必须承认我对indexedDB还很陌生

0ve6wy6x

0ve6wy6x1#

versionchange事务还允许您读写。您只需要访问onupgradeneded函数中为您创建的事务。

function go() {
  var req = indexeddb.open(...);
  req.onupgradeneeded = function(event) {

    // note that event.target === req === this, use whatever you like
    var db = event.target.result;

    // createObjectScore implicitly uses the versionchange txn running 
    // here, without telling you, basically a convenience function
    var objectStore = db.createObjectStore(...);

    // the important part that i am describing in this answer, 
    // grab the handle of the versionchange txn 
    // that is already running and was created for you
    // note again that event.target === req, you could just do
    // req.transaction or this.transaction here.
    // note this is a property of the open request, not a method. do NOT
    // confuse this with the method transaction() that is used to create a 
    // new transaction.
    var txn = event.target.transaction;

    // note that txn.objectStore(...) will work here, because the 
    // createObjectStore call earlier guarantees the store exists here
    // within the implicit upgrade txn
    var addRequest = txn.objectStore(...).add('value');

    // side note: if in previous line we did:
    // var objectStoreRetrievedFromTxn = txn.objectStore(...);
    // then that variable is equal to the same variable returned from 
    // db.createObjectStore earlier in this function. Both are simply handles 
    // (references, pointers, whatever you want to call it) to the store.

    // kind of dumb, but you could do this just to log something
    addRequest.onsuccess = function() {console.log('Success!');};
  };

  // called once upgrade txn completes (if it even needed to run), 
  // and db is opened
  req.onsuccess = function(event) {
    console.log('upgrade txn completed and db is now connected');
    // here, create whatever readwrite or readonly txns you want, note these 
    // txns are separate from and different than the versionchange txn from 
    // before, because that is a unique transaction only available within 
    // onupgradeneeded. however, both versionchange and readwrite are similar
    // in that both support calls to put or add
  };
}

您遇到此错误的原因是,您试图在版本更改事务仍在运行时启动第二个事务。

bybem2ql

bybem2ql2#

在尝试加载对象存储之前,需要检查版本更改事务是否完成:

request.onupgradeneeded =
    function(event) {
        db = event.target.result;
        var store = db.createObjectStore('Files', {keyPath:"files"});
        var transaction = event.target.transaction;

        transaction.oncomplete =
            function(event) {    
                // Now store is available to be populated
            }
    }
xcitsw88

xcitsw883#

在版本更改中,您不需要为事务指定作用域。这始终是所有预先设置的对象存储。transaction.objectStore('text')在这里,您正试图打开一个具有索引名称的对象存储,这是行不通的。如果要访问索引,您需要先转到对象存储。
需要在对象存储上添加数据。

function go(){var req = window.indexedDB.open("Uploader", 1), db;
req.onerror=function(e){console.log('Error')};
req.onsuccess = function(e){db=e.target.result;};
req.onupgradeneeded = function(e){
    console.log(db);
    db=e.target.result;
    var trans=e.target.transaction;
    var os = db.createObjectStore('Files', {keyPath:"files"});
        os.createIndex('text', 'text_file', {unique:false})
    var objectstore=  trans.objectStore("Files");
    var addreq = objectstore.add('Instructions.js');
        addreq.onsuccess = function(e)  {console.log('Success!');console.dir(e)}
}}

给予这个

ergxz8rk

ergxz8rk4#

总是使用官方的IndexedDB规范。MDN谎言,有很多不准确的地方,尤其是当涉及到类型的时候。

const request = indexedDB.open("library", 3);
request.onupgradeneeded = function(event) {
  const db = request.result;
  const transaction = request.transaction;
  if (event.oldVersion < 3) {
    const bookStore = transaction.objectStore("books");
    const yearIndex = bookStore.createIndex("by_year", "year");
  }
};

相关问题