Change material during rendering / frame_change [crash]

Hey, I’m trying to change material on many objects during frame change with python.
In viewport everything works fine but during Animation Rendering(cycles or eevee) it crashes immediately or a few frames later.

My system can’t handle more than 500 cubes. A small delay in foreach is also no solution. Does anyone have an idea? (Ps. Shader animation is no option)

It crashes during rendering with this Error: EXCEPTION_ACCESS_VIOLATION

import bpy

scene = bpy.context.scene
objs = [obj for obj in scene.objects if obj.type == 'MESH']
m = bpy.data.materials
mats = [m['Red'], m['Green'], m['Blue']]

def frame_change_post(scene, depsgraph):
    nr = scene.frame_current % 3
    print("Frame Change: ", nr)
    
    for obj in objs:
        obj.active_material = mats[nr]
 
bpy.app.handlers.frame_change_post.clear()
bpy.app.handlers.frame_change_post.append(frame_change_post)