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

NextJs中Zustand persist调用clearStorage出现TypeError问题求助

解决Zustand persist的clearStorage调用报错问题

错误原因

你直接通过useItemsStore.persist访问persist方法是错误的——Zustand中被persist包装后的store,persist属性并不挂载在useItemsStore这个hook函数本身,而是挂载在调用hook后返回的store实例上。直接访问函数的persist属性会得到undefined,自然无法读取clearStorage方法。

正确解决方案

方案1:在组件内获取store实例后调用

import { useItemsStore } from '@/stores/itemsStore'
import { Button } from '@/components/ui/button'

export default function StateInput() {
  // 调用hook获取store实例
  const itemsStore = useItemsStore()

  const clearStorage = () => {
    // 从实例的persist属性调用clearStorage
    itemsStore.persist.clearStorage()
  }

  return (
    <Button className='destructive-color' onClick={clearStorage}>
      Clear Storage
    </Button>
  )
}

方案2:直接在onClick中通过getState调用

如果不想额外声明函数,也可以用Zustand的getState方法直接获取store实例:

<Button 
  className='destructive-color' 
  onClick={() => useItemsStore.getState().persist.clearStorage()}
>
  Clear Storage
</Button>

确认你的store创建方式

确保你的store是用persist正确包装的,示例如下:

// stores/itemsStore.ts
import { create } from 'zustand'
import { persist } from 'zustand/middleware'

export const useItemsStore = create(
  persist(
    (set, get) => ({
      items: [],
      addItem: (item) => set({ items: [...get().items, item] }),
      // 其他store方法
    }),
    {
      name: 'items-storage', // localStorage存储的key
    }
  )
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 23:25:11