IndexedDB 错误:试图对不允许突变的数据库执行突变操作

4sup72z8  于 2022-12-09  发布在  IndexedDB
关注(0)|答案(3)|浏览(277)
console.log(db); //db object exists
console.log(db.objectStoreNames.contains('test')); //true - object store exists

var transaction = db.transaction(['test'], 'readwrite'); // this line is causing the error

A mutation operation was attempted on a database that did not allow mutations." code: "6

为什么我得到这个错误?我的数据库和对象存储存在?我失去了我的头脑!:D任何帮助都非常感谢!
谢谢

xggvc2p6

xggvc2p61#

此错误的一个潜在原因:Firefox不支持在私密浏览窗口中使用IndexedDB。请参阅https://bugzilla.mozilla.org/show_bug.cgi?id=1639542https://github.com/jakearchibald/idb/issues/81

z9ju0rcb

z9ju0rcb2#

我只是尝试现在的chrome,Safari上的Mac OS X,并没有发现任何错误.
我在http://dev.yathit.com/ydn-db/using/schema.html上做如下操作(该页面加载ydn.db.storage对象)

schema = {stores: [{name: 'test'}]}
st = new ydn.db.Storage('test1', schema)
// ... wait for async
db = st.db()
db.transaction(['test'], 'readwrite')

旧chrome使用1而不是“readwrite”,但我不认为这是一个原因。

ubof19bj

ubof19bj3#

这样的错误太多了,只有这篇文章http://dev.opera.com/articles/introduction-to-indexeddb/说明了原因----“使用IndexedDB,我们数据库上的每个操作或事务都必须在回调函数中发生”。
这是我的一个简单的例子,请使用chrome的devtool-〉resource-〉indexedDB查看它;(如果indexedDB中没有任何内容,请尝试刷新浏览器)
html部分:

<form id="form1">
    <label for="task">What do you need to do?</label>
    <input type="text" name="task" id="task" value="" required>
    <button type="submit" id="submit">Save entry</button>
</form>

脚本部分:

var idb = indexedDB.open('niangzi10', 2);
    var dbobject; // Define a global variable to hold our database object
    idb.onsuccess = function (evt) {
        console.log("success");
        if (dbobject === undefined) {
            dbobject = evt.target.result;
        }
    }
    idb.onupgradeneeded = function (evt) {
        dbobject = evt.target.result;
        if (evt.oldVersion < 1) {
            dbobject.createObjectStore('tasks', { autoIncrement: true });
        }
    }
    //transaction operation in callback function
    var form1 = document.getElementById('form1');
    form1.addEventListener('submit', function (evt) {
        'use strict';
        evt.preventDefault();

        var entry = {}, transaction, objectstore, request;
        entry = { name: document.querySelector("#task").value };

        // Open a transaction for writing
        transaction = dbobject.transaction(['tasks'], 'readwrite');
        objectstore = transaction.objectStore('tasks');
        // Save the entry object
        request = objectstore.add(entry);
        transaction.oncomplete = function (evt) {
            alert("'" + document.querySelector("#task").value + "'has been insert into indexedDB;please check it using chrome's devtool->resource->indexedDB(if nothing,refresh browser);");
        };

    });

相关问题