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

Zustand结合TypeScript使用Persist时因缺失options参数报错

解决Zustand persist中间件缺少options参数的报错

问题描述

使用Zustand的persist持久化功能时触发TypeScript报错:persist.d.ts(95, 210): An argument for 'options' was not provided,报错代码如下:

import { create, StateCreator } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { CountryData } from './countryTypes';

interface CountrySlice {
    countries: CountryData[];
    fetchCountries: () => void;
}

const countrySlice: StateCreator<CountrySlice> = (set) => ({
    countries: [],
    fetchCountries: async () => {
        const res = await fetch('https://restcountries.com/v3.1/all');
        set({ countries: await res.json() });
    },
});


export const useCountryStore = create<CountrySlice>()(
    persist(
        devtools((...a) => ({
            ...countrySlice(...a),
        }))
    )
);

原因分析

Zustand新版本的persist中间件强制要求传入第二个参数options对象,这个对象至少需要包含name字段——用于在本地存储(默认是localStorage)中标识当前store的键名,否则TypeScript会抛出参数缺失的错误。

解决方案

给persist方法添加第二个参数,传入包含name的配置对象,修改后的代码如下:

import { create, StateCreator } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import { CountryData } from './countryTypes';

interface CountrySlice {
    countries: CountryData[];
    fetchCountries: () => void;
}

const countrySlice: StateCreator<CountrySlice> = (set) => ({
    countries: [],
    fetchCountries: async () => {
        const res = await fetch('https://restcountries.com/v3.1/all');
        set({ countries: await res.json() });
    },
});


export const useCountryStore = create<CountrySlice>()(
    persist(
        devtools((...a) => ({
            ...countrySlice(...a),
        })),
        // 添加persist的options配置,name为必填项
        {
            name: 'country-store' // 本地存储中对应的键名,可自定义
            // 可选配置:比如切换存储方式为sessionStorage
            // storage: sessionStorage
        }
    )
);

可选配置说明

除了必填的name,还可以在options中添加其他自定义配置:

  • storage: 指定存储介质,默认是localStorage,也可设置为sessionStorage或自定义存储实现
  • partialize: 选择需要持久化的状态字段,比如只持久化countries:partialize: (state) => ({ countries: state.countries })
  • onRehydrateStorage: 重新加载存储数据时的钩子函数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 14:43:13