You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Dexie useLiveQuery hook报错dexie.liveQuery is not a function

这个问题同时存在版本不兼容和代码编写错误,不是库本身的bug。

核心原因

  • 版本匹配问题:dexie-react-hooks v1.0.7要求依赖Dexie v3.1.0及以上版本,你当前使用的Dexie v3.0.3版本未内置liveQueryAPI,是触发报错的直接原因。
  • API调用错误:useLiveQuery的第一个入参要求是返回查询对象的函数,不能直接传入查询实例,否则即使升级版本也无法正常运行。
  • 边界判断缺失:useLiveQuery在查询完成前会返回undefined,直接调用map方法会触发新的类型错误。

修复步骤

  1. 升级Dexie到符合要求的版本,执行命令:
npm install dexie@^3.1.0
  1. 调整组件代码,修改后的完整代码如下:
import React from 'react';
import Dexie from 'dexie'
import { useLiveQuery } from 'dexie-react-hooks'

const myDb = new Dexie('myTable');
myDb.version(1).stores(
  {
    items: "id,name,startDate,endDate"
  }
)

function App() {
  // 第一个参数改为返回查询的函数
  const items = useLiveQuery(() => myDb.items.orderBy('name'), []);

  // 加边界判断避免空值报错
  const itemViews = items?.map(item => { return <div>{item.name}</div> })

  return (
    <div className="App">
      <ul>
        {itemViews}
      </ul>
    </div>
  );
}

export default App;

内容的提问来源于stack exchange,提问作者Brian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 10:06:02