最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - A non-serializable value was detected in an action - Stack Overflow

programmeradmin4浏览0评论

I am getting react_devtools_backend.js:4026 A non-serializable value was detected in an action, in the path: payload.config.adapter this error when I sign up. I am using here redux-toolkit, react version 18, node version 16.

SignUp.jsx

import React, { useState, useEffect } from 'react'
import { Link, useNavigate } from "react-router-dom"
import MetaData from "../../more/Metadata"
import { ToastContainer, toast } from 'react-toastify';
import "react-toastify/dist/ReactToastify.css";
import { useForm } from "react-hook-form";
import { useDispatch, useSelector } from 'react-redux'
import { signUp } from "../../store/slices/authSlice"


const SignUp = () => {
const { register, handleSubmit } = useForm()
const dispatch = useDispatch()
const navigate = useNavigate()

const { status, error } = useSelector((state) => state.auth)
// console.log(auth);
// const [error, setError] = useState()


 const submitForm = (data) => {
 data.email = data.email.toLowerCase()
 const action = signUp(data)
 dispatch(action)
}

useEffect(() => {
    if (error) {
        toast.error(error);

    }

    if (status === "failed") {
        toast.error("Registration failed!");

    }

    if (status === 'success') {
       toast.success("Registration Successfull");
       navigate('/login')
    }
  }, [status, error])




 return (
     <>
         <MetaData title="Sign up" />
         <div className="h-screen">
             <div className="container px-6 py-12 h-full">
             <div className="flex justify-center items-center flex-wrap h-full g-6 
             text-gray-800">
             <div className="md:w-8/12 lg:w-6/12 mb-12 md:mb-0">
             <img
                src=" 
                login-form/draw2.svg"
                className="w-full"
                alt="Phoneimage"
             />
            </div>
           <div className="md:w-8/12 lg:w-5/12 lg:ml-20">
              <form onSubmit={handleSubmit(submitForm)}>
                  <div className="mb-6">
                      <input
                          id='userName'
                          type="text"
                          autoComplete='off'
                          required
                          {...register('userName', { required: true, maxLength: 30 
                          })}
                          className="form-control block w-full px-4 py-2 text-xl 
                          font-normal text-gray-700 bg-white bg-clip-padding border 
                           border-solid border-gray-300 rounded transition ease-in- 
                          out m-0 focus:text-gray-700 focus:bg-white focus:border- 
                          blue-600 focus:outline-none"
                          placeholder="Username"
                          />

                 </div>


                 <div className="mb-6">
                     <input
                         type="email"
                         autoComplete='off'
                         required
                         {...register('email')}
                         className="form-control block w-full px-4 py-2 text-xl font- 
                         normal text-gray-700 bg-white bg-clip-padding border border- 
                         solid border-gray-300 rounded transition ease-in-out m-0 
                         focus:text-gray-700 focus:bg-white focus:border-blue-600 
                         focus:outline-none"
                         placeholder="Email"
                        />
                </div>


                <div className="mb-6">
                    <input
                        id="password"
                        type="password"
                        {...register('password')}
                        className="form-control block w-full px-4 py-2 text-xl font- 
                        normal text-gray-700 bg-white bg-clip-padding border border- 
                        solid border-gray-300 rounded transition ease-in-out m-0 
                        focus:text-gray-700 focus:bg-white focus:border-blue-600 
                        focus:outline-none"
                         placeholder="Password"
                      />
                </div>

                <div className="flex md:flex-row flex-col md:gap-0 gap-4 items-center 
                 justify-between mb-6">
                    <div className="shrink-0">
                        <img className="object-cover w-16 h-16 rounded-full"
                      src=" 
                      1345143__340.png" alt="profilephoto" />
                    </div>
                    <input
                        type="file"
                        name="avatar"
                         accept="image/*"
                         className="text-sm text-grey-500
                         file:mr-5 file:py-3 file:px-10
                         file:rounded-full file:border-0
                         file:text-md file:font-semibold  file:text-white
                         file:bg-gradient-to-r file:from-blue-400 file:to-amber-200
                         hover:file:cursor-pointer hover:file:opacity-80
                       " />
                </div>




                <button
                  type="submit"
                  className="inline-block px-7 py-3 bg-blue-600 text-white font- 
                  medium text-sm leading-snug uppercase rounded shadow-md hover:bg- 
                   blue-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg 
                  focus:outline-none focus:ring-0 active:bg-blue-800 active:shadow-lg 
                  transition duration-150 ease-in-out w-full"
                  data-mdb-ripple="true"
                  data-mdb-ripple-color="light"
                >
                Sign Up
                </button>

                <div
                  className="flex items-center my-4 before:flex-1 before:border-t 
                   before:border-gray-300 before:mt-0.5 after:flex-1 after:border-t 
                   after:border-gray-300 after:mt-0.5"
                >
                    <p className="text-center font-semibold mx-4 mb-0">OR</p>
                </div>

                <div className="w-full text-center">
                    <p>Already have an Account. <Link className="font-bold text-lg 
                    cursor-pointer text-orange-500 underline" 
                    to="/login">Login</Link></p>
                </div>



              </form>
            </div>
          </div>
        </div>
      </div>
      <ToastContainer
          position="top-right"
          autoClose={5000}
          hideProgressBar={false}
          newestOnTop={false}
          closeOnClick
          rtl={false}
          pauseOnFocusLoss
          draggable
          pauseOnHover
       />
    </>
  )
}

export default SignUp

store.js

import { configureStore, bineReducers } from "@reduxjs/toolkit";
import productReducer from "./slices/productSlice"
import authReducer from "./slices/authSlice"
import {
    persistStore,
    persistReducer,
    FLUSH,
    REHYDRATE,
    PAUSE,
    PERSIST,
    PURGE,
    REGISTER,
 } from 'redux-persist'
 import storage from 'redux-persist/lib/storage'


 const persistConfig = {
     key: 'root',
     version: 1,
     storage,
 }

 const rootReducer = bineReducers({
    auth: authReducer,
    product: productReducer
 })

 const persistedReducer = persistReducer(persistConfig, rootReducer)

 export const store = configureStore({
    reducer: persistedReducer,
    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware({
            serializableCheck: {
                ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
            },
        }),
    })

  export let persistor = persistStore(store)

authSlice.js

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import authAPI from '../../api/authApi'

export const signUp = createAsyncThunk(
    'auth/signUp',
    async (data, { rejectWithValue }) => {
        try {
            const result = await authAPI.register(data)

            return result
        } catch (error) {
            return rejectWithValue(error.response)
        }
    }
)

export const login = createAsyncThunk(
    'auth/login',
    async (data, { rejectWithValue }) => {
        try {
            return await authAPI.login(data)
        } catch (error) {
            return rejectWithValue(error.response)
        }
    }
)

const authSlice = createSlice({
    name: "auth",
    initialState: {
    user: {},
    status: 'idle',
    error: null,
    userToken: null
},
reducers: {},

extraReducers: {

    [signUp.pending]: (state) => {
        state.loading = true
        state.error = null
    },
    [signUp.fulfilled]: (state, action) => {
        state.loading = false
        state.success = action.payload.user // registration successful
    },
    [signUp.rejected]: (state, { payload }) => {
        state.loading = false
        state.error = payload
    },


   }
 })

 export default authSlice.reducer

authApi.js import axiosClient from "./axiosClient"

const authAPI = {
    register: async(data) => {
        const url = "/api/v2/registeration"
        return await axiosClient.post(url, data)
     },

    login: async(data) => {
        const url = "/api/v2/login"
        return await axiosClient.post(url, data)
    }
 }

 export default authAPI

axiosClient.js

import axios from 'axios'

const axiosClient = axios.create({
    baseURL: ";,
    headers: {
        'Content-Type': 'application/json',
    },
    paramsSerializer: (params) => params,
})

axiosClient.interceptors.request.use(async (config) => {
   const token = localStorage.getItem('token')
   const auth = token ? `Bearer ${token}` : ''
   config.headersmon['Authorization'] = auth

   return config
})

axiosClient.interceptors.response.use(
    (response) => {
        if (response && response.data) {
            return response.data
        }

        return response
     },
     (error) => {
        throw error
     }
  )

 export default axiosClient

error

react_devtools_backend.js:4026 A non-serializable value was detected in an action, in 
the path: `payload.config.adapter`. Value: ƒ xhrAdapter(config) {
 return new Promise(function dispatchXhrRequest(resolve, reject) {
 var requestData = config.data;
var requestHeaders = config.headers;
var responseType = config.resp… 
Take a look at the logic that dispatched this action:  {type: 'auth/signUp/rejected', 
payload: {…}, meta: {…}, error: {…}} 
(See  
serializable-why-should-my-action-types-be-constants) 
(To allow non-serializable values see:  
guide#working-with-non-serializable-data)
overrideMethod @ react_devtools_backend.js:4026
(anonymous) @ serializableStateInvariantMiddleware.ts:195
measureTime @ utils.ts:10
(anonymous) @ serializableStateInvariantMiddleware.ts:183
(anonymous) @ index.js:20
(anonymous) @ immutableStateInvariantMiddleware.ts:258
dispatch @ redux.js:691
(anonymous) @ createAsyncThunk.ts:651
 step @ RefreshUtils.js:264
 (anonymous) @ RefreshUtils.js:264
 rejected @ RefreshUtils.js:264

I am getting react_devtools_backend.js:4026 A non-serializable value was detected in an action, in the path: payload.config.adapter this error when I sign up. I am using here redux-toolkit, react version 18, node version 16.

SignUp.jsx

import React, { useState, useEffect } from 'react'
import { Link, useNavigate } from "react-router-dom"
import MetaData from "../../more/Metadata"
import { ToastContainer, toast } from 'react-toastify';
import "react-toastify/dist/ReactToastify.css";
import { useForm } from "react-hook-form";
import { useDispatch, useSelector } from 'react-redux'
import { signUp } from "../../store/slices/authSlice"


const SignUp = () => {
const { register, handleSubmit } = useForm()
const dispatch = useDispatch()
const navigate = useNavigate()

const { status, error } = useSelector((state) => state.auth)
// console.log(auth);
// const [error, setError] = useState()


 const submitForm = (data) => {
 data.email = data.email.toLowerCase()
 const action = signUp(data)
 dispatch(action)
}

useEffect(() => {
    if (error) {
        toast.error(error);

    }

    if (status === "failed") {
        toast.error("Registration failed!");

    }

    if (status === 'success') {
       toast.success("Registration Successfull");
       navigate('/login')
    }
  }, [status, error])




 return (
     <>
         <MetaData title="Sign up" />
         <div className="h-screen">
             <div className="container px-6 py-12 h-full">
             <div className="flex justify-center items-center flex-wrap h-full g-6 
             text-gray-800">
             <div className="md:w-8/12 lg:w-6/12 mb-12 md:mb-0">
             <img
                src="https://mdbcdn.b-cdn/img/Photos/new-templates/bootstrap- 
                login-form/draw2.svg"
                className="w-full"
                alt="Phoneimage"
             />
            </div>
           <div className="md:w-8/12 lg:w-5/12 lg:ml-20">
              <form onSubmit={handleSubmit(submitForm)}>
                  <div className="mb-6">
                      <input
                          id='userName'
                          type="text"
                          autoComplete='off'
                          required
                          {...register('userName', { required: true, maxLength: 30 
                          })}
                          className="form-control block w-full px-4 py-2 text-xl 
                          font-normal text-gray-700 bg-white bg-clip-padding border 
                           border-solid border-gray-300 rounded transition ease-in- 
                          out m-0 focus:text-gray-700 focus:bg-white focus:border- 
                          blue-600 focus:outline-none"
                          placeholder="Username"
                          />

                 </div>


                 <div className="mb-6">
                     <input
                         type="email"
                         autoComplete='off'
                         required
                         {...register('email')}
                         className="form-control block w-full px-4 py-2 text-xl font- 
                         normal text-gray-700 bg-white bg-clip-padding border border- 
                         solid border-gray-300 rounded transition ease-in-out m-0 
                         focus:text-gray-700 focus:bg-white focus:border-blue-600 
                         focus:outline-none"
                         placeholder="Email"
                        />
                </div>


                <div className="mb-6">
                    <input
                        id="password"
                        type="password"
                        {...register('password')}
                        className="form-control block w-full px-4 py-2 text-xl font- 
                        normal text-gray-700 bg-white bg-clip-padding border border- 
                        solid border-gray-300 rounded transition ease-in-out m-0 
                        focus:text-gray-700 focus:bg-white focus:border-blue-600 
                        focus:outline-none"
                         placeholder="Password"
                      />
                </div>

                <div className="flex md:flex-row flex-col md:gap-0 gap-4 items-center 
                 justify-between mb-6">
                    <div className="shrink-0">
                        <img className="object-cover w-16 h-16 rounded-full"
                      src="https://cdn.pixabay./photo/2016/04/22/04/57/graduation- 
                      1345143__340.png" alt="profilephoto" />
                    </div>
                    <input
                        type="file"
                        name="avatar"
                         accept="image/*"
                         className="text-sm text-grey-500
                         file:mr-5 file:py-3 file:px-10
                         file:rounded-full file:border-0
                         file:text-md file:font-semibold  file:text-white
                         file:bg-gradient-to-r file:from-blue-400 file:to-amber-200
                         hover:file:cursor-pointer hover:file:opacity-80
                       " />
                </div>




                <button
                  type="submit"
                  className="inline-block px-7 py-3 bg-blue-600 text-white font- 
                  medium text-sm leading-snug uppercase rounded shadow-md hover:bg- 
                   blue-700 hover:shadow-lg focus:bg-blue-700 focus:shadow-lg 
                  focus:outline-none focus:ring-0 active:bg-blue-800 active:shadow-lg 
                  transition duration-150 ease-in-out w-full"
                  data-mdb-ripple="true"
                  data-mdb-ripple-color="light"
                >
                Sign Up
                </button>

                <div
                  className="flex items-center my-4 before:flex-1 before:border-t 
                   before:border-gray-300 before:mt-0.5 after:flex-1 after:border-t 
                   after:border-gray-300 after:mt-0.5"
                >
                    <p className="text-center font-semibold mx-4 mb-0">OR</p>
                </div>

                <div className="w-full text-center">
                    <p>Already have an Account. <Link className="font-bold text-lg 
                    cursor-pointer text-orange-500 underline" 
                    to="/login">Login</Link></p>
                </div>



              </form>
            </div>
          </div>
        </div>
      </div>
      <ToastContainer
          position="top-right"
          autoClose={5000}
          hideProgressBar={false}
          newestOnTop={false}
          closeOnClick
          rtl={false}
          pauseOnFocusLoss
          draggable
          pauseOnHover
       />
    </>
  )
}

export default SignUp

store.js

import { configureStore, bineReducers } from "@reduxjs/toolkit";
import productReducer from "./slices/productSlice"
import authReducer from "./slices/authSlice"
import {
    persistStore,
    persistReducer,
    FLUSH,
    REHYDRATE,
    PAUSE,
    PERSIST,
    PURGE,
    REGISTER,
 } from 'redux-persist'
 import storage from 'redux-persist/lib/storage'


 const persistConfig = {
     key: 'root',
     version: 1,
     storage,
 }

 const rootReducer = bineReducers({
    auth: authReducer,
    product: productReducer
 })

 const persistedReducer = persistReducer(persistConfig, rootReducer)

 export const store = configureStore({
    reducer: persistedReducer,
    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware({
            serializableCheck: {
                ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
            },
        }),
    })

  export let persistor = persistStore(store)

authSlice.js

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import authAPI from '../../api/authApi'

export const signUp = createAsyncThunk(
    'auth/signUp',
    async (data, { rejectWithValue }) => {
        try {
            const result = await authAPI.register(data)

            return result
        } catch (error) {
            return rejectWithValue(error.response)
        }
    }
)

export const login = createAsyncThunk(
    'auth/login',
    async (data, { rejectWithValue }) => {
        try {
            return await authAPI.login(data)
        } catch (error) {
            return rejectWithValue(error.response)
        }
    }
)

const authSlice = createSlice({
    name: "auth",
    initialState: {
    user: {},
    status: 'idle',
    error: null,
    userToken: null
},
reducers: {},

extraReducers: {

    [signUp.pending]: (state) => {
        state.loading = true
        state.error = null
    },
    [signUp.fulfilled]: (state, action) => {
        state.loading = false
        state.success = action.payload.user // registration successful
    },
    [signUp.rejected]: (state, { payload }) => {
        state.loading = false
        state.error = payload
    },


   }
 })

 export default authSlice.reducer

authApi.js import axiosClient from "./axiosClient"

const authAPI = {
    register: async(data) => {
        const url = "/api/v2/registeration"
        return await axiosClient.post(url, data)
     },

    login: async(data) => {
        const url = "/api/v2/login"
        return await axiosClient.post(url, data)
    }
 }

 export default authAPI

axiosClient.js

import axios from 'axios'

const axiosClient = axios.create({
    baseURL: "https://emerce--webapp.herokuapp.",
    headers: {
        'Content-Type': 'application/json',
    },
    paramsSerializer: (params) => params,
})

axiosClient.interceptors.request.use(async (config) => {
   const token = localStorage.getItem('token')
   const auth = token ? `Bearer ${token}` : ''
   config.headers.mon['Authorization'] = auth

   return config
})

axiosClient.interceptors.response.use(
    (response) => {
        if (response && response.data) {
            return response.data
        }

        return response
     },
     (error) => {
        throw error
     }
  )

 export default axiosClient

error

react_devtools_backend.js:4026 A non-serializable value was detected in an action, in 
the path: `payload.config.adapter`. Value: ƒ xhrAdapter(config) {
 return new Promise(function dispatchXhrRequest(resolve, reject) {
 var requestData = config.data;
var requestHeaders = config.headers;
var responseType = config.resp… 
Take a look at the logic that dispatched this action:  {type: 'auth/signUp/rejected', 
payload: {…}, meta: {…}, error: {…}} 
(See https://redux.js/faq/actions#why-should-type-be-a-string-or-at-least- 
serializable-why-should-my-action-types-be-constants) 
(To allow non-serializable values see: https://redux-toolkit.js/usage/usage- 
guide#working-with-non-serializable-data)
overrideMethod @ react_devtools_backend.js:4026
(anonymous) @ serializableStateInvariantMiddleware.ts:195
measureTime @ utils.ts:10
(anonymous) @ serializableStateInvariantMiddleware.ts:183
(anonymous) @ index.js:20
(anonymous) @ immutableStateInvariantMiddleware.ts:258
dispatch @ redux.js:691
(anonymous) @ createAsyncThunk.ts:651
 step @ RefreshUtils.js:264
 (anonymous) @ RefreshUtils.js:264
 rejected @ RefreshUtils.js:264
Share Improve this question asked Aug 6, 2022 at 12:50 Pavitar SharmaPavitar Sharma 1492 gold badges4 silver badges18 bronze badges 1
  • Did you read the error message all the way through? It gives a lot of guidance as to how to fix this problem. – Andy Commented Aug 6, 2022 at 12:59
Add a ment  | 

3 Answers 3

Reset to default 8

You're returning the entire Axios response object from your async thunks. That includes some of the Axios config setup. Don't do that :)

Instead, just return response.data or similar, so that only plain data values are being returned.

It is dispatching but should use state.user = action.payload.user and remove from state.success . Use this method.....

[signUp.fulfilled]: (state, action) => {
    state.loading = false
    state.success = true // registration successful
    state.user = action.payload.user //--------------//
},

I had the same error with the rtk query. The issue was in one of endpoints

      await addDoc(collection(db, "blogs"), {

I forgot to import db, so undefined passed to the addDoc and since undefined is not serializable I got the error. Probably somewhere one of the variables are undefined

发布评论

评论列表(0)

  1. 暂无评论