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

React Mantine(v6.0.13+Vite)中CSP拦截内联样式的解决求助

解决Mantine 6.0.13 + Vite下CSP内联样式拒绝问题

核心原因

Mantine基于Emotion实现CSS-in-JS,部分动态组件(如Modal、Tooltip)会生成带内联style属性的元素;同时Vite开发环境可能注入内联样式,这些都触发了CSP的限制。

解决方案

1. 给Emotion配置Nonce

让Emotion生成的所有内联样式自动带上你配置的nonce,匹配CSP规则:

  • 首先在服务端将随机生成的nonce注入页面的meta标签(确保每个请求的nonce唯一):
    <meta name="csp-nonce" content="你的随机nonce值">
    
  • 在应用入口文件(如main.tsx)中配置Emotion的CacheProvider:
    import { CacheProvider } from '@emotion/react';
    import createCache from '@emotion/cache';
    import { MantineProvider } from '@mantine/core';
    
    // 从meta标签获取nonce
    const nonce = document.querySelector('meta[name="csp-nonce"]')?.getAttribute('content') || '';
    
    const emotionCache = createCache({
      key: 'mantine-emotion-cache',
      nonce,
    });
    
    function App() {
      return (
        <CacheProvider value={emotionCache}>
          <MantineProvider>
            {/* 你的应用内容 */}
          </MantineProvider>
        </CacheProvider>
      );
    }
    
    export default App;
    
  • 确保HTTP头的CSP指令中的nonce与meta标签的完全一致。

2. 调整Vite配置适配CSP

  • 开发环境:Vite的HMR机制可能注入内联样式,可通过禁用CSS内联注入减少冲突:
    // vite.config.ts
    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    
    export default defineConfig({
      plugins: [react()],
      css: {
        inject: false, // 禁用内联样式注入,生成独立style标签
      },
      server: {
        headers: {
          'Content-Security-Policy': "default-src http://localhost; style-src 'self' 'nonce-你的随机值' http://localhost; font-src 'self';",
        },
      },
    });
    
  • 生产环境:Vite会自动将样式打包为独立文件,只需确保Emotion的nonce配置生效即可。

3. 避免直接使用内联style属性

检查代码中是否通过style或sx属性直接写内联样式,尽量改用Mantine的className或Emotion的css函数处理,确保样式被Emotion托管并带上nonce。

4. 临时放宽CSP(不推荐)

如果上述方案无法快速生效,可临时在style-src中添加'unsafe-hashes'(针对内联style属性)或'unsafe-inline'(不推荐,降低安全性),但仅用于调试,生产环境必须移除。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 20:26:10