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

使用Tauri+React+Redux开发聊天应用遇类型错误求助

问题解决:Redux Toolkit中Property 'app' does not exist on type 'WritableDraft<{ channelId: null; channelName: null; }>'错误

错误根源

你在appSlice的setChannelId reducer里错误尝试访问state.app,但该slice的state本身就是{channelId: null, channelName: null}——因为在store.ts中,根状态的app字段对应的就是appReducer,所以slice内部的state不需要额外嵌套app属性。

当你手动添加app: null到initialState后,根状态的结构变成了state.app.app,导致你的selector(state.app.channelId)实际取的是错误路径,最终引发应用无法渲染的问题。

修复步骤

1. 修正appSlice的reducer逻辑

把setChannelId里的错误代码改成直接修改channelId(另外注意你误用了+=,设置ID应该是赋值操作):

import { PayloadAction, createSlice } from '@reduxjs/toolkit';
import type { RootState } from '../app/store';

// 给state定义明确类型,避免模糊类型问题
interface AppState {
  channelId: string | null;
  channelName: string | null;
}

export const appSlice = createSlice({
    name: 'app',
    initialState: {
        channelId: null,
        channelName: null,
    } as AppState,
    reducers: {
        setChannelId: (state, action: PayloadAction<string>) => {
            // 直接修改state的channelId字段
            state.channelId = action.payload;
        },
        // 若需要设置频道名称,可添加对应reducer
        setChannelName: (state, action: PayloadAction<string>) => {
            state.channelName = action.payload;
        }
    },
});

export const { setChannelId, setChannelName } = appSlice.actions;

export const selectChannelId = (state: RootState) => state.app.channelId;
export const selectChannelName = (state: RootState) => state.app.channelName;

export default appSlice.reducer;

2. 移除initialState中的app: null

恢复initialState的原始结构,不需要额外的app嵌套字段。

3. 验证根状态结构

你的store.ts配置是正确的:

export const store =  configureStore({
    reducer: {
        user: userReducer,
        app: appReducer, // 根状态的app字段对应appSlice的状态
    }
});

此时根状态的结构为:

{
  user: UserState,
  app: {
    channelId: string | null,
    channelName: string | null
  }
}

你的selector(state.app.channelId)完全匹配这个结构,能正确获取对应值。

额外建议

  • 给slice的state定义明确的TypeScript接口,避免null带来的类型模糊问题
  • 确保reducer中的操作符合业务逻辑:设置ID用赋值=而非累加+=

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 10:53:10