Yes, you can volunteer while on a temporary visa as long as you are not compensated in cash or kind.
For F-1 OPT, if the volunteer work is meant to count toward your OPT compliance, it must be at least 20 hours per week and related to your field of study. If it’s purely additional volunteer work (e.g., helping at events, reviewing research papers) and not counted for OPT compliance, there’s no issue, but check with your DSO.
However, you cannot volunteer for a for-profit company, as that could violate labor laws, though the violation would be on the company’s part, not yours.