React项目对接Next.js时出现TypeError: Cannot read properties of undefined (reading 'REACT_APP_SC_ATTR')错误求助
Hey there, let's work through this error you're facing—it's almost always linked to either styled-components integration with Material UI in a Next.js environment, or issues with environment variable accessibility. Here are the most practical fixes based on your code snippet:
1. Fix Environment Variable Prefix for Next.js
REACT_APP_SC_ATTR is a styled-components environment variable used to customize style attribute prefixes, but Next.js doesn't recognize the REACT_APP_ prefix for client-accessible variables—it uses NEXT_PUBLIC_ instead. That's probably why the variable is showing up as undefined.
- Update your
.env.local(or environment-specific env file) with the correct prefix:NEXT_PUBLIC_SC_ATTR=data-styled - If you're manually referencing this variable anywhere in your code, swap
process.env.REACT_APP_SC_ATTRforprocess.env.NEXT_PUBLIC_SC_ATTR.
2. Simplify Your Theme Provider Nesting
Your current code nests both MuiThemeProvider and what looks like styled-components's ThemeProvider—this creates unnecessary complexity and can lead to conflicts. Material UI's ThemeProvider (imported from @mui/material/styles) works seamlessly with StyledEngineProvider when using styled-components as the styling engine.
Simplify your code to this cleaner version:
import { StyledEngineProvider, ThemeProvider, createTheme } from '@mui/material/styles'; // ... your theme definition here <StyledEngineProvider injectFirst> <ThemeProvider theme={createTheme(theme)}> <AuthProvider>{Component}</AuthProvider> </ThemeProvider> </StyledEngineProvider>
This removes redundant nesting and eliminates potential clashes between the two theme systems.
3. Verify Dependency Version Compatibility
Make sure styled-components and Material UI are running compatible versions—MUI v5 requires styled-components v5.x or later. Run these commands to check and update if needed:
# Check current installed versions npm list styled-components @mui/material # Update to latest compatible versions npm install styled-components@latest @mui/material@latest
4. Configure Next.js for Styled Components SSR
Next.js needs extra setup to handle styled-components during server-side rendering. You can configure this in one of two ways:
Option A: Use Next.js Compiler
Add this to your next.config.js:
module.exports = { compiler: { styledComponents: true, }, }
Option B: Babel Plugin
Create or update a .babelrc file in your project root:
{ "presets": ["next/babel"], "plugins": [["styled-components", { "ssr": true }]] }
This ensures styled-components properly handles environment variables and style injection during SSR, which can resolve the undefined property error.
内容的提问来源于stack exchange,提问作者Greg Turner

