Javascript indexDB error: The database is not running a version change transaction

阅读(10459)

使用indexDB的时候遇到报错:

Uncaught DOMException: Failed to execute 'createObjectStore' on 'IDBDatabase': The database is not running a version change transaction.

原因在于只能在onupgradeneeded 时新建DB,而不能在onsuccess时做此操作。

来自 MDN 的说明

When you create a new database or increase the version number of an existing database (by specifying a higher version number than you did previously, when Opening a database), the onupgradeneeded event will be triggered and an IDBVersionChangeEvent object will be passed to any onversionchange event handler set up on request.result (i.e., db in the example). In the handler for the upgradeneeded event, you should create the object stores needed for this version of the database.

修正后的示例代码如下:

window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

let DB = function(dbName, callback, options) {
    let openRequest;

    !options && (options = {});
    openRequest = indexedDB.open(dbName, options.dbVersion || 1);

    openRequest.onsuccess = e => {
        this.dbHandler = e.target.result;
        // 不能在onsuccess新建db
    };
    openRequest.onblocked = options.onblocked || function() {};
    openRequest.onerror = options.onerror || function() {};
    openRequest.onupgradeneeded = e => {
        this.dbHandler = e.target.result;
        // 只能在此新建DB
        this.dbHandler.createTable('KAIFAGE_COM', {keyPath: 'name'})
    };

    this.dbName = dbName;

    return this;
}