Unhandled Promise Rejection: QuotaExceededError: The quota has been exceeded
浏览器本地存储(LocalStorage/SessionStorage)容量上限为5MB,超限会报错。可通过计算函数检测当前用量:统计所有键值对的UTF-16编码总字节数(每个字符2字节),将结果转换为KB/MB等易读格式。大型项目或存储图片时容易触达上限,建议定期检查清理。示例代码可输出当前使用量,帮助开发者监控存储情况。
·

当控制台报这个错误的时候,往往是因为本地存储超过5M限额了,所以就会报错,在浏览器环境中,LocalStorage和SessionStorage都是上限5M的容量,超过之后就不能再存储东西了,一般来讲不会超过,但是对于大型一点的项目,或者这里面存储图片的情况,就会出现这种错误。
如果查看使用了多少?
// 计算当前已使用的localStorage容量
function getLocalStorageUsage() {
let total = 0;
for (let key in localStorage) {
if (localStorage.hasOwnProperty(key)) {
total += (localStorage[key].length + key.length) * 2; // UTF-16编码,每个字符2字节
}
}
return total; // 返回字节数
}
// 转换为更友好的格式
function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
// 使用示例
const usage = getLocalStorageUsage();
console.log(`LocalStorage使用量: ${formatBytes(usage)}`);
可以看到,确实快超了:

查看SessionStorage容量
sessionStorage的存储容量上限也是5M,查看使用了多少:
function getSessionStorageUsage() {
let total = 0;
for (let key in sessionStorage) {
if (sessionStorage.hasOwnProperty(key)) {
total += (sessionStorage[key].length + key.length) * 2;
}
}
return total;
}
const sessionUsage = getSessionStorageUsage();
console.log(`SessionStorage使用量: ${formatBytes(sessionUsage)}`);
解决方案
当LocalStorage容量超出限制时,可以采取IndexedDB方案,因为IndexedDB的存储容量更大

火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。
更多推荐
所有评论(0)